import {BaseBooleanComboBoxFilter} from "@webbpm/base-package";
import {IFilterParams, IDoesFilterPassParams, IFilterComp} from "ag-grid-community";


export class FileAvailableFilterComp extends BaseBooleanComboBoxFilter implements IFilterComp {
  private filterValue: boolean | undefined = undefined;
  private params!: IFilterParams;

  init(params: IFilterParams): void {
    this.params = params;
    this.createComboBox("ag-combobox-file-filter");
    this.populateComboBoxWithFixedValues();

    this.comboBox.addEventListener("change", () => this.onComboBoxChanged());
  }

  protected populateComboBoxWithFixedValues(): void {
    const options = [
      { label: "Все", value: undefined },
      { label: "Файл присутствует", value: true },
      { label: "Файл отсутствует", value: false }
    ];

    this.comboBox.innerHTML = "";
    options.forEach(({ label }) => {
      const option = document.createElement("option");
      option.textContent = label;
      this.comboBox.appendChild(option);
    });
  }

  protected onComboBoxChanged(): void {
    const selectedIndex = this.comboBox.selectedIndex;

    this.filterValue =
        selectedIndex === 1 ? true :
        selectedIndex === 2 ? false :
        undefined;

    this.params.filterChangedCallback();
  }

  doesFilterPass(params: IDoesFilterPassParams): boolean {
    const cellValue = params.data[this.params.colDef.field!];
    return this.filterValue === undefined || cellValue === this.filterValue;
  }

  isFilterActive(): boolean {
    return this.filterValue !== undefined;
  }

  getModel(): any {
    return this.filterValue === undefined
           ? undefined
           : { filter: this.filterValue, type: "equals" };
  }

  setModel(model: any): void {
    this.filterValue = model ? model.filter : undefined;

    if (this.filterValue === true) {
      this.comboBox.selectedIndex = 1;
    }
    else if (this.filterValue === false) {
      this.comboBox.selectedIndex = 2;
    }
    else {
      this.comboBox.selectedIndex = 0;
    }

    this.params.filterChangedCallback();
  }

  getGui(): HTMLElement {
    return this.eGui;
  }
}