import {AnalyticalScope, Filter, FilterComponent, FilterUtil} from "@webbpm/base-package";
import {DropdownTreeViewComponent} from "../field/DropdownTreeViewComponent";

@AnalyticalScope(DropdownTreeViewComponent)
export class DropdownTreeViewFilterComponent extends FilterComponent {

  public isBusinessId: boolean;
  private treeViewComponent: DropdownTreeViewComponent;

  initialize() {
    super.initialize();
    this.treeViewComponent = this.getScript(DropdownTreeViewComponent) as DropdownTreeViewComponent;
  }

  public getFilter(): Filter {
    let model = this.treeViewComponent.value;

    if (!model && this.treeViewComponent.cachedValue) {
      let value = this.isBusinessId
                  ? this.treeViewComponent.cachedValue.businessId
                  : this.treeViewComponent.cachedValue.id;
      return FilterUtil.singleValueFilter(this.getObjectId(), value, this.operation);
    }
    else if (model) {
      let value = this.isBusinessId ? model.businessId : model.id;
      return FilterUtil.singleValueFilter(this.getObjectId(), value, this.operation);
    }
    else {
      return null;
    }
  }

  resetFilter(): Promise<void> | void {
    this.treeViewComponent.clearValue();
    return super.resetFilter();
  }
}
