import {AdvancedProperty, AnalyticalScope, Behavior, Visible} from "@webbpm/base-package";
import {DropdownTreeViewComponent} from "../../../component/field/DropdownTreeViewComponent";
import {TreeItemDto} from "../../../generated/component/model/TreeItemDto";

@AnalyticalScope(DropdownTreeViewComponent)
export class DropdownTreeViewModelFilterValue extends Behavior {

  public isBusinessId: boolean;
  @AdvancedProperty()
  public separator: string;

  @Visible()
  public getIds(): string {
    const treeViewComponent = this.getScript(
        DropdownTreeViewComponent) as DropdownTreeViewComponent;
    let model: TreeItemDto = treeViewComponent.value;
    const dtos: TreeItemDto[] = [];

    if (!model && treeViewComponent.cachedValue) {
      model = treeViewComponent.cachedValue;
    }
    if (model) {
      if (!model.parentId) {
        return null;
      }
      dtos.push(model);
      this.fillArray(dtos, model);
    }
    const ids: string[] = dtos.map(value => this.isBusinessId ? value.businessId : value.id);
    return this.separator ? ids.join(this.separator) : ids.join();
  }

  private fillArray(dtos: TreeItemDto[], dto: TreeItemDto): void {
    if (dto.children) {
      dtos.push(...dto.children);
      dto.children.forEach(value => this.fillArray(dtos, value));
    }
  }
}
