import { IFilterParams } from 'ag-grid-community';
import { FilterMode } from '../../model/common-model';
import { Container } from 'aurelia-framework';
import { ServiceBase } from "../../data/service-base";
import * as breeze from 'breeze-client';
import { Config } from '../../config';
import { BaseRelationFilter } from './base-relation-filter';

export class ManyToManyFilter<T extends breeze.Entity> extends BaseRelationFilter<T> {

  protected filterType: string = 'manyToMany';

  private filterMode: FilterMode = FilterMode.Or;
  private arrayIndex: number;

  public init(params: IFilterParams & { serviceName: string, service: ServiceBase<T>, arrayField: string }): void {
    this.config = Container.instance.get(Config);
    this.buildService(params);

    let fields = params.column.getColDef().field.split('.');
    if (params.arrayField == null) {
      params.arrayField = fields[0];
    }
    (params as any).arrayIndex = fields.findIndex(x => x == params.arrayField);
    super.init(params);
    this.fieldPath = fields.slice((params as any).arrayIndex + 2);
  }

  public async setupContentGui(): Promise<string> {
    await super.setupContentGui();
    return `
    <div class="floating-filter__body__many-to-many">
      <div class="floating-filter__body__search">
        <ui-field t="[label]common:grid.searchShort">
          <ui-input type="text" value.bind="valueSearch & debounce:500" t="[placeholder]common:grid.searchShort" autofocus.one-time="true" allow-clear.one-time="true">
            <ui-input-addon icon="digi-search"></ui-input-addon>
          </ui-input>
        </ui-field>
        <div class="ui-btn__wrapper w-100 ui-margin--t--xs" ui-theme="secondary">
          <div class="ui-btn__inner no-focus" style="display: flex;">
            <a class="ui-btn w-100" click.delegate="toggleFilterMode(0)" tabindex="0" data-active.bind="filterMode == 0">\${ 'common:grid.or' | t }</a>
            <a class="ui-btn w-100" click.delegate="toggleFilterMode(1)" tabindex="0" data-active.bind="filterMode == 1">\${ 'common:grid.and' | t }</a>
          </div>
        </div>
        <div class="ui-check__wrapper" if.bind="showEmptyFieldsCheckbox">
          <ui-checkbox checked.bind="displayEmptyFields">\${ 'grid.displayEmptyFields' | t }</ui-checkbox>
        </div>
      </div> 

      <div class="floating-filter__body__many-to-many__list">
        <div repeat.for="filterValue of filterValues" if.bind="!filterValue.hide" class="floating-filter__body__many-to-many__list__elem">
          <ui-checkbox checked.bind="filterValue.selected" title.bind="filterValue.name">\${filterValue.name}</ui-checkbox>
        </div>
      </div>
    </div>`;
  }

  public getModel() {
    let model = super.getModel();
    if (model != null) {
      Object.assign(model, { filterMode: this.filterMode, arrayIndex: this.arrayIndex, displayEmptyFields: this.displayEmptyFields });
    }
    return model;
  }

  protected extendFilterValuesChangesModel() {
    return { filterMode: this.filterMode, arrayIndex: (this.params as any).arrayIndex, displayEmptyFields: this.displayEmptyFields };
  }

  protected setModelHook(model: any): void {
    this.filterMode = model.filterMode;
    this.displayEmptyFields = model.displayEmptyFields;
    this.arrayIndex = model.arrayIndex;
  }

  public setupContentGuiSideFilter(): string {
    return `
    <div class="col s12 m12 l12">
      <ui-field label.bind="params.colDef.headerName">
        <ui-select multiple t="[placeholder]general.chooseAnOption" value.bind="selectedIds"
          data-source.bind="service.gridDataSource" options-text="${this.fieldPath.join(".")}"
          filter-properties.bind="['${this.fieldPath.join(".")}']" options-value="id">
          <option></option>
          <option repeat.for="value of filterValuesSelected" value.bind="value.id" selected.bind="true">
            \${value.name}</option>
          <ui-select-header-template>
            <div class="ui-btn__wrapper w-100 ui-margin--t--xs" ui-theme="secondary">
              <div class="ui-btn__inner no-focus" style="display: flex;">
                <a class="ui-btn w-100" click.delegate="toggleFilterMode(0)" tabindex="0" data-active.bind="filterMode == 0">\${ 'common:grid.or' | t }</a>
                <a class="ui-btn w-100" click.delegate="toggleFilterMode(1)" tabindex="0" data-active.bind="filterMode == 1">\${ 'common:grid.and' | t }</a>
              </div>
            </div>
            <div class="ui-check__wrapper" if.bind="showEmptyFieldsCheckbox">
                <ui-checkbox checked.bind="displayEmptyFields">\${ 'grid.displayEmptyFields' | t }</ui-checkbox>
            </div>
          </ui-select-header-template>
        </ui-select>
      </ui-field>
    </div>
   `;
  }

  public toggleFilterMode(filterMode: FilterMode) {
    this.filterMode = filterMode;
    this.setModel({ filterType: this.filterType, filter: this.filterValues, filterMode: this.filterMode, arrayIndex: (this.params as any).arrayIndex, displayEmptyFields: this.displayEmptyFields });
  }
}
