import { EnumSelected } from './../../../model/common-model';
import { EnumFilterHelper } from './enum-filter-helper';
import { IFilterParams } from 'ag-grid-community';
import BaseFilter from '../base-filter';

export class EnumFilter extends BaseFilter {
  public filterHelper: EnumFilterHelper;

  public init(params: IFilterParams & { category: string, enum: any }): void {
    this.filterHelper = new EnumFilterHelper((newVal, oldVal) => this.filterValuesChanged(newVal, oldVal), params.enum, params.category);

    this.filterChangedCallback = params.filterChangedCallback;
    super.init(params);
  }

  public async onOpenDropDown() {
    if (this.isDestroyed()) {
      return;
    }
    await this.filterHelper.onOpenDropDown();
  }

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

  public resetFilter() {
    this.filterHelper.resetFilter();
  }

  public removeFilterValue(filterValue: EnumSelected): void {
    filterValue.selected = false;
  }

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

  public async setupContentGui(): Promise<string> {
    await this.onOpenDropDown();
    return this.filterHelper.setupContentGui();
  }

  public filterValuesChanged(newVal: boolean, oldVal: boolean) {
    if (newVal != oldVal) {
      this.DROPDOWN_NAME = this.getModelAsString();
      const instance = this.params.api.getFilterInstance((this.params as IFilterParams).colDef.field);
      instance.setModel({ filterType: 'enum', filter: this.filterHelper.filterValues });
    }
  }

  public getValue(): Array<EnumSelected> {
    return this.filterHelper.getValue();
  }

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

  public getModel(): any {
    return this.isFilterActive() ? { filterType: 'enum', filter: this.filterHelper.filterValues } : null;
  }

  public setModel(model: any): void {
    if (model == null) {
      if (this.isDestroyed()) {
        this.dispose();
        this.filterHelper.filterValues = [];
      } else {
        this.resetFilter();
      }
    } else if (model.filterType == 'enum') {
      this.filterHelper.getEnumerated(model.filter);
    }
    this.DROPDOWN_NAME = this.getModelAsString();
    this.filterHelper.setSelectedValues();
    this.filterChangedCallback();
  }
}
