import { IFilterParams } from 'ag-grid-community';
import BaseFilter from '../base-filter';
import { Container } from 'aurelia-framework';
import { DateFilterHelper } from './date-filter-helper';
import { I18N } from 'aurelia-i18n';

export class DateFilter extends BaseFilter {

  public filterHelper: DateFilterHelper;

  public init(params: IFilterParams): void {
    this.i18n = Container.instance.get(I18N);
    this.filterHelper = new DateFilterHelper((newVal: Date | boolean | number, oldVal: Date | boolean | number) => this._propertyChangedHelper(newVal, oldVal), () => this.resetFilterCallBack());

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

  private _propertyChangedHelper(newVal: Date | boolean | number, oldVal: Date | boolean | number) {
    if (!this.firstTime && !this.filterHelper.ignorePropertyChanges) {
      this.DROPDOWN_NAME = this.getModelAsString();
      if (newVal != oldVal) {
        this.setModelInstance();
      }
    }
  }

  public setModelInstance() {
    const instance = this.params.api.getFilterInstance((this.params as IFilterParams).colDef.field);
    instance.setModel(this.getModelFilter());
  }

  public setModel(model: any): void {
    if (model == null) {
      this.resetFilter();
    } else if (model.filterType == 'date') {

      // Convert model
      model.fromDate = model.dateFrom;
      model.toDate = model.dateTo;
      model.selectedDatePreFilter = model.datePreFilter;

      if (this.filterHelper.isAnyDifferent(this.filterHelper, model)) {
        this.filterHelper.ignorePropertyChanges = true;
        this.filterHelper.assignToThis(model);

        this.resetFilterCallBack();

        this.taskQueue.queueMicroTask(() => this.filterHelper.ignorePropertyChanges = false);
      }
    }
    this.filterChangedCallback();
  }

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

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

  public getModel(): any {
    return this.filterHelper.getModel('inRange');
  }

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

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

  private getFilter(): string {
    return this.filterHelper.getFilter();
  }

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

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

  public removeFilterValue(): void {
    this.resetFilter();
  }

  private resetFilterCallBack() {
    this.DROPDOWN_NAME = this.getModelAsString();
    this.setModelInstance();
  }

  public getModelFilter(): any {
    let modelFilter = this.filterHelper.getModelFilter();
    return modelFilter;
  }
}