import { Config } from '../../../index';
import { Container } from 'aurelia-framework';
import { observable } from "aurelia-binding";
import { I18N } from "aurelia-i18n";


export class StringFilterHelper {
    public text: string;
    @observable
    public textDisplayed: string;
    public displayEmptyFields: boolean = false;

    private i18n: I18N;
    private config: Config

    constructor(private searchMinLength: number, public isMultiple: boolean, private textChangedCallback) {
        this.i18n = Container.instance.get(I18N);
        this.config = Container.instance.get(Config);
    }

    public isFilterActive(): boolean {
        return (this.text != null && this.text != this.config.agGridConfig.stringSeparatorAgGridFilter) || this.displayEmptyFields;
    }

    public resetFilter(): void {
        this.textDisplayed = null;
        this.displayEmptyFields = false;
    }

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

    public getModelAsString(): string {
        return this.getValue() ?? this.i18n.tr('grid.noFilter', { ns: "common" });
    }

    public setupContentGuiSideFilter(): string {
        return `<div class="col s12 m12 l12">
            <ui-field label.bind="params.colDef.headerName">
                <ui-input value.bind="filterHelper.textDisplayed & debounce:500"></ui-input>
            </ui-field>
        </div>`;
    }

    public textDisplayedChanged(newVal: string, oldVal: string) {
        if (newVal == '') {
            newVal = null;
        }
        if (oldVal == '') {
            oldVal = null;
        }

        if (newVal != oldVal) {
            this.text = newVal;
            if ((newVal == null || newVal.length >= this.searchMinLength) && this.textChangedCallback) {
                this.textChangedCallback(newVal, oldVal);
            }
        }
    }
}