import { IFilterParams } from "ag-grid-community";
import { observable } from 'aurelia-binding';
import BaseFilter from "../base-filter";
import { BooleanFilterHelper } from "./boolean-filter-helper";

export class BooleanFilter extends BaseFilter {
  @observable
  public selectedIndex: number;

  public selected: string;
  private groupName: string;
  public filterHelper: BooleanFilterHelper;

  public init(params: IFilterParams): void {
    this.groupName = Math.random().toString();

    this.filterHelper = new BooleanFilterHelper();
    this.filterChangedCallback = params.filterChangedCallback;

    if (this.i18n != null) {
      this.filterHelper.setFilterNames([this.i18n.tr('grid.noFilter', { ns: "common" }), this.i18n.tr('grid.yes', { ns: "common" }), this.i18n.tr('grid.no', { ns: "common" })]);
    }

    this.selected = this.filterHelper.getFilterNone();
    this.selectedIndex = 0;

    super.init(params);
  }

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

  public removeFilterValue(): void {
    this.selectedIndex = this.filterHelper.FILTER_VALUES.findIndex(x => x == this.filterHelper.FILTER_NONE);
  }

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

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

  public getValue(): boolean {
    return this.filterHelper.getValue(this.selectedIndex);
  }

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

  public selectedIndexChanged(newVal: number, oldVal: number) {
    if (newVal != oldVal && !this.firstTime) {
      this.DROPDOWN_NAME = this.getModelAsString();
      const instance = this.params.api.getFilterInstance((this.params as IFilterParams).colDef.field);
      instance.setModel({ "filterType": "boolean", "filter": this.filterHelper.getFilterValue(this.selectedIndex) });
    }
  }

  public isFilterActive(): boolean {
    return this.selected !== this.filterHelper.getFilterNone();
  }

  public getModel(): any {
    if (this.selected === this.filterHelper.getFilterNone()) return null;
    return { "filterType": "boolean", "filter": this.selected };
  }

  public setModel(model: any): void {
    if (model == null) {
      this.selected = this.filterHelper.getFilterNone();
    }
    else if (model.filterType == 'boolean') {
      this.selected = model.filter;
    }
    this.selectedIndex = this.filterHelper.getFilterValueIndex(this.selected);
    this.filterChangedCallback();
  }
}
