import {
  AdvancedProperty,
  AnalyticalScope,
  ComboBox,
  ComboBoxModel,
  Filter,
  FilterUtil,
  TextFormatter,
  Visible
} from "@webbpm/base-package";
import {ErvuFilterComponent} from "./ErvuFilterComponent";

@AnalyticalScope(ComboBox)
export class ComboboxFilterComponent extends ErvuFilterComponent {

  public isBusinessId: boolean;
  @AdvancedProperty()
  public defaultValue: string;
  @AdvancedProperty()
  public formatter: TextFormatter;
  @AdvancedProperty()
  public saveFilterValue: boolean;

  private filterValue: any;

  getFilter(): Filter {
    const combobox = this.getScript(ComboBox) as ComboBox;
    const model: ComboBoxModel = combobox.getValueAsModel();
    let value;

    if (model) {
      value = this.isBusinessId ? model.businessId : model.id;
    }

    if (this.saveFilterValue) {
      if (value || value === 0) {
        if (this.filterValue !== value) {
          this.filterValue = value;
        }
      }
      else {
        value = this.getFilterValue();
      }
    }

    if (value || value === 0) {
      return FilterUtil.singleValueFilter(
          this.getObjectId(), this.formatter ? this.formatter.format(value) : value,
          this.operation);
    }
    else {
      return null;
    }
  }

  @Visible()
  public getFilterValue(): any {
    return this.filterValue || this.filterValue === 0 ? this.filterValue : this.defaultValue;
  }
}
