import { BooleanFilterHelper } from './boolean-filter-helper';
import { Container, observable } from 'aurelia-framework';
import { IFloatingFilterParams, FilterChangedEvent } from "ag-grid-community";
import { I18N } from "aurelia-i18n";
import BaseFloatingFilter from "../base-floating-filter";

export class BooleanFloatingFilter extends BaseFloatingFilter {
  @observable
  public selectedIndex: number;

  private groupName: string;
  public filterHelper: BooleanFilterHelper;

  public init(params: IFloatingFilterParams & { noFilterName: string, trueFilterName: string, falseFilterName: string, noFilterIcon: string, trueFilterIcon: string, falseFilterIcon: string }): void {
    this.filterHelper = new BooleanFilterHelper();
    super.init(params);

    this.groupName = Math.random().toString();

    this.i18n = Container.instance.get(I18N);
    if (this.i18n != null) {
      this.filterHelper.setFilterNames([this.i18n.tr(params.noFilterName || 'grid.noFilter', { ns: "common" }), this.i18n.tr(params.trueFilterName || 'grid.yes', { ns: "common" }), this.i18n.tr(params.falseFilterName || 'grid.no', { ns: "common" })]);
      this.filterHelper.setFilterIcons([(params.noFilterIcon || 'digi-filter'), (params.trueFilterIcon || 'digi-valid'), (params.falseFilterIcon || 'digi-cross')]);
    }

    this.selectedIndex = 0;
    this.setDropDown();

    super.setupGui();
  }

  public resetFilter(): void {
    this.selectedIndex = this.filterHelper.getFilterValueIndex(this.filterHelper.getFilterNone());
  }

  public setupContentGui(): string {
    return this.filterHelper.setupContentGui(this.groupName);
  }

  public setupContentGuiSideFilter(): string {
    return this.filterHelper.setupContentGuiSideFilter();
  }

  public getModelAsString(): string {
    return this.filterHelper.getModelAsString(this.selectedIndex);
  }

  public selectedIndexChanged(newVal: number, oldVal: number) {
    if (newVal != oldVal && !this.firstTime) {
      this.setDropDown();
      (this.params as IFloatingFilterParams).parentFilterInstance((instance) => {
        instance.setModel({ "filterType": "boolean", "filter": this.filterHelper.getFilterValue(this.selectedIndex) });
      });
    }
  }

  public onParentModelChanged(parentModel: any, filterChangedEvent?: FilterChangedEvent): void {
    this.selectedIndex = ((parentModel && parentModel.filter) ? (this.filterHelper.getFilterValueIndex(parentModel.filter)) : 0);
    this.setDropDown();
  }

  private setDropDown() {
    this.DROPDOWN_NAME = this.getModelAsString();
    this.DROPDOWN_ICON = this.filterHelper.getFilterIcon(this.selectedIndex);
  }
}
