import { GridHeaderBar } from './../../resources/elements/grid-header-bar';
import { EnumSelected } from './../../model/common-model';
import { autoinject } from 'aurelia-framework';
import { ColDef, IFilter } from "ag-grid-community";
import { FloatingBoxViewModel } from './floating-box';
import { SideFilter } from '../../resources/filters/SideFilter';

export interface Filter {
  field: string;
  type: string;
  instance: IFilter;
  curentElem: Element;
}
export interface EnumSelectedFilter extends EnumSelected {
  id: number | string;
}

@autoinject
export class FilterViewBox extends FloatingBoxViewModel {
  private currentFilters: Filter[];

  constructor(private containerInstance: GridHeaderBar) {
    super('./filter-view-box.html');
  }

  public async activate(config: any) {
    await super.activate(config);
    this.createFilterArray();
  }
  public attached() {
    this.currentFilters.forEach(x => {
      ((x.instance as any) as SideFilter)?.getGuiSideFilter(x.curentElem);
    })
  }

  public getTitle(): string {
    return this.containerInstance.i18n.tr('common:grid.filterBy');
  }

  public resetFilter() {
    this.currentFilters.forEach(filter => {
      if (((filter.instance as any) as SideFilter).resetFilter != null) {
        ((filter.instance as any) as SideFilter).resetFilter();
      }
    });
  }

  private createFilterArray() {
    if (this.currentFilters == null) {
      this.currentFilters = new Array<Filter>();
    } else {
      this.currentFilters.splice(0);
    }
    let columnDefs = this.sortFilters(this.containerInstance.gridOptions?.columnDefs);
   
    let supressMenu = this.containerInstance.gridOptions?.defaultColDef?.suppressMenu;
    if (supressMenu == true) {
      columnDefs = columnDefs.filter(c => (<ColDef<any>>c).suppressMenu == false);
    } else {
      columnDefs = columnDefs.filter(c => (<ColDef<any>>c).suppressMenu != true);
    }

    for (let colDefs of columnDefs) {
      let currentFilter = {} as Filter;
      currentFilter.field = (colDefs as ColDef).field;
      currentFilter.type = (colDefs as ColDef).type as string;
      currentFilter.instance = this.containerInstance.gridOptions.api?.getFilterInstance(currentFilter.field);
      if (currentFilter.instance == null || ((currentFilter.instance as any) as SideFilter).getGuiSideFilter == null) {
        continue;
      }
      this.currentFilters.push(currentFilter);
    }
  }

  private sortFilters(columnDefs: ColDef<any>[]) {
    return columnDefs.sort(
      (a: ColDef & { filterParams: any }, b: ColDef & { filterParams: any }) => {
        if (a.filterParams?.filterOrder != null) {
          if (b.filterParams?.filterOrder == null) {
            return -1;
          }
          return a.filterParams.filterOrder - b.filterParams.filterOrder;
        }
        return a.headerName.localeCompare(b.headerName);
      }
    );
  }
}
