import { ApplyColumnStateParams, ColDef } from 'ag-grid-community';
import { GridOptions as AgGridOptions } from 'ag-grid-community';

export class AgGridSortingHelper {
  constructor(private gridOptions: GridOptions) { }

  public applyDefaultSortModel() {
    this.gridOptions?.columnApi.applyColumnState(this.getDefaultSortModel());
  }
  public getDefaultSortModel(): ApplyColumnStateParams {
    return {
      state: (<ColDef[]>this.gridOptions?.columnDefs)
        .filter(colDef => colDef.sort != null)
        .map(({ field, sort }) => { return { colId: field, sort }; }),
      defaultState: { sort: null }
    }
  }
  public isCurrentSortDefault(): boolean {
    let currentSort: SortDef[] = this.gridOptions?.columnApi.getColumnState().filter(x => x.sort != null).sortBy('colId');
    let defaultSort: SortDef[] = this.getDefaultSortModel().state.sortBy('colId');
    return currentSort.length == defaultSort.length && false == currentSort.some((current, index) => defaultSort[index].colId != current.colId || defaultSort[index].sort != current.sort);
  }

  public hasAnySorting(): boolean {
    return this.gridOptions?.columnApi?.getColumnState().some(x => x.sort != null);
  }
}

export class SortDef {
  colId: string;
  sort?: "asc" | "desc"
}

export interface GridOptions extends AgGridOptions {
  fixedFilters: boolean;
  adjustColumns: boolean;
}
