import { Grid, OptionBase, createElement, createIcon } from "../ui";
import { nullOrEmpty } from "../utility";

export default class TemplateSelector extends OptionBase {
    _var = {
        /**
         * @private
         * @type {number}
         */
        assetId: -1,
        /**
         * @private
         * @type {HTMLElement}
         */
        container: null,
        el: {
            /**
             * @private
             * @type {HTMLInputElement}
             */
            inputSearch: null,
            /**
             * @private
             * @type {Grid}
             */
            grid: null
        }
    };

    /**
     * @event
     * @type {(this: TemplateSelector, template: any) => void}
     */
    onSelected;

    constructor(opt = {
        /** @type {(flag: boolean) => void} */
        loading: null,
        /** @type {() => void} */
        close: null,
        /** @type {(assetId: number, search: string) => Promise<any[]>} */
        requestTemplates: null
    }) {
        super(opt);
    }

    get assetId() { return this._var.assetId }
    set assetId(id) {
        this._var.assetId = id;
        this.refresh();
    }

    get title() { return this.r('FLTL_01604', 'Inspection Templates') }

    get currentTemplate() { return this._var.el.grid.currentItem }

    loading(flag) {
        if (typeof this._option.loading === 'function') {
            this._option.loading(flag);
        }
    }

    refresh() {
        const requestTemplates = this._option.requestTemplates;
        if (typeof requestTemplates !== 'function') {
            return;
        }
        const el = this._var.el;
        this.loading(true);
        requestTemplates(this._var.assetId, el.inputSearch.value)
            .then(data => el.grid.source = data)
            .finally(() => this.loading(false));
    }

    select(item) {
        if (typeof this.onSelected !== 'function') {
            return false;
        }
        this.onSelected(item);
    }

    create() {
        const tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)) + 3;
        const inputSearch = createElement('input', input => {
            input.type = 'text';
            input.placeholder = this.r('FLTL_02606', 'Search');
            input.tabIndex = tabIndex + 1;
            input.className = 'ui-input';
            input.addEventListener('keypress', e => e.key === 'Enter' && this.refresh());
        });
        const gridContent = createElement('div', div => {
            div.className = 'popup-selector-content';
            div.style.height = '400px';
        });
        const grid = new Grid(gridContent, this.r);
        grid.columns = [
            {
                key: 'IssueId',
                type: Grid.ColumnTypes.Icon,
                width: 30,
                enabled: false,
                resizable: false,
                filter: it => nullOrEmpty(it.IssueId) ? '' : 'cubes'
            },
            { key: 'Name', caption: this.r('FLTL_01966', 'Name'), width: 390 },
            { key: 'Notes', caption: this.r('FLTL_02012', 'Notes'), width: 630 }
        ];
        grid.onRowDblClicked = index => {
            const item = grid.source[index];
            this.select(item);
            if (typeof this._option.close === 'function') {
                this._option.close();
            }
        };
        grid.init();
        grid.element.tabIndex = tabIndex + 2;
        this._var.el = {
            inputSearch,
            grid
        };

        // content
        const container = createElement('div', 'popup-selector',
            createElement('div', 'popup-selector-header',
                createElement('h3', h3 => h3.innerText = this.r('FLTL_02261', 'Please select a template.'))
            ),
            createElement('div', 'popup-selector-function',
                createElement('div', 'search-box',
                    inputSearch,
                    createElement('span', span => {
                        span.addEventListener('click', () => this.refresh());
                    },
                        createIcon('fa-light', 'search')
                    )
                )
            ),
            gridContent
        );
        this._var.container = container;
        return container;
    }
}