import { Container } from 'aurelia-framework';
import { I18N } from 'aurelia-i18n';
import { IFloatingFilterParams, FilterChangedEvent } from 'ag-grid-community';
import BaseFloatingFilter from '../base-floating-filter';
import { StringFilterHelper } from './string-filter-helper';

export class StringFloatingFilter extends BaseFloatingFilter {
    public filterHelper: StringFilterHelper;

    public init(params: IFloatingFilterParams & { searchMinLength: number, isMultiple: boolean }): void {
        this.filterHelper = new StringFilterHelper(params.searchMinLength ?? 0, params.isMultiple ?? true, () => this.textDisplayedChanged());
        super.init(params);

        this.showInputField = true;
        this.showDropdown = false;
        this.i18n = Container.instance.get(I18N);

        super.setupGui();
    }

    public setupContentGui(): string {
        return `<div class="floating-filter__body__search">
              <ui-input type="text" value.bind="filterHelper.textDisplayed & 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>
              <div class="ui-check__wrapper" if.bind="showEmptyFieldsCheckbox">
                <ui-checkbox checked.bind="filterHelper.displayEmptyFields">\${ 'grid.displayEmptyFields' | t }</ui-checkbox>
              </div>
            </div>`;
    }

    public setupInputField(): string {
        return "<input value.bind='filterHelper.textDisplayed & debounce:500' style='display: inline-flex; margin: 0; height: 100%;'>";
    }

    public textDisplayedChanged() {
        (this.params as IFloatingFilterParams).parentFilterInstance((instance) => {
            instance.setModel({ filterType: 'text', type: 'contains', filter: this.filterHelper.text, isMultiple: this.filterHelper.isMultiple, displayEmptyFields: this.filterHelper.displayEmptyFields });
        });
    }

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

    public onParentModelChanged(parentModel: any, filterChangedEvent?: FilterChangedEvent): void {
        this.filterHelper.textDisplayed = ((parentModel && parentModel.filter) ? (parentModel.filter as string) : null);
    }

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

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

    protected applyObservers() {
        this.dispose(); // Making sure that everything is disposed before re-adding observers
        this.disposables.push(this.bindingEngine.propertyObserver(this.filterHelper, 'displayEmptyFields').subscribe(this.textDisplayedChanged.bind(this)));
    }
}