import { OptionBase, Popup, createElement, showAlert } from "../ui";
import AssetSelector from "./assetselector";
import TemplateSelector from "./templateselector";

export default class InspectionWizard extends OptionBase {
    _var = {
        /**
         * @private
         * @type {number}
         */
        index: 0,
        /**
         * @private
         * @type {HTMLElement[]}
         */
        containers: [],
        /**
         * @private
         * @type {AssetSelector}
         */
        assetSelector: null,
        asset: null,
        template: null,
        /**
         * @private
         * @type {Popup}
         */
        popup: null
    };

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

    constructor(opt = {
        /**
         * @private
         * @type {(assetId: number, search: string) => Promise<any[]>}
         */
        requestTemplates: null,
        /**
         * @private
         * @type {(hidden: boolean, search?: string, groups?: string[], jobsites?: number[], codes?: string[]) => Promise<any[]>}
         */
        requestAssets: null,
        /**
         * @private
         * @type {() => Promise<{AssetGroups: any[], Codes: any[], Jobsites: any[]}>}
         */
        requestAssetParams: null
    }) {
        super(opt);
    }

    async create(asset) {
        const option = this._option;
        const loading = flag => this._var.popup.loading = flag;
        const assetSelector = new AssetSelector({
            ignoreHidden: true,
            loading,
            requestAssets: option.requestAssets,
            requestAssetParams: option.requestAssetParams
        });
        this._var.assetSelector = assetSelector;
        const templateSelector = new TemplateSelector({
            loading,
            requestTemplates: option.requestTemplates
        });
        this._var.templateSelector = templateSelector;
        assetSelector.onSelected = async asset => {
            this._var.asset = asset;
            this._var.template = null;
            if (typeof option.getAssetUncompletedInspection === 'function') {
                const report = await option.getAssetUncompletedInspection(asset.Id);
                if (report) {
                    showAlert(assetSelector.title, this.r('FLTL_03601', 'The following inspection needs to be certified: ') + report.Value);
                    return false;
                }
            }
            this._changePage(1);
            templateSelector.assetId = asset.Id;
        };
        templateSelector.onSelected = template => {
            this._var.template = template;
            this._select();
            this._var.popup.close();
        }
        this._var.containers = [
            assetSelector.create(),
            templateSelector.create()
        ];
        const popup = new Popup({
            title: this.r('FLTL_00121', 'Add Inspection'),
            content: createElement('div', null, ...this._var.containers),
            persistent: true,
            buttons: [
                {
                    text: this.r('FLTL_00447', 'Back'),
                    trigger: () => {
                        this._changePage(0);
                        return false;
                    }
                },
                {
                    text: this.r('FLTL_01973', 'Next'),
                    trigger: async () => {
                        const asset = assetSelector.currentAsset;
                        if (asset == null) {
                            showAlert(assetSelector.title, this.r('FLTL_02269', 'Please select an Asset.'));
                            return false;
                        }
                        if (typeof option.getAssetUncompletedInspection === 'function') {
                            const report = await option.getAssetUncompletedInspection(asset.Id);
                            if (report) {
                                showAlert(assetSelector.title, this.r('FLTL_03601', 'The following inspection needs to be certified: ') + report.Value);
                                return false;
                            }
                        }
                        this._var.asset = asset;
                        this._var.template = null;
                        this._changePage(1);
                        templateSelector.assetId = asset.Id;
                        return false;
                    }
                },
                {
                    text: this.r('FLTL_02057', 'OK'),
                    trigger: () => {
                        const template = templateSelector.currentTemplate;
                        if (template == null) {
                            showAlert(templateSelector.title, this.r('FLTL_02261', 'Please select a template.'));
                            return false;
                        }
                        this._var.template = template;
                        this._select();
                    }
                },
                { text: this.r('FLTL_00499', 'Cancel') }
            ]
        });
        this._var.popup = popup;
        popup.create();
        if (asset) {
            this._changePage(1);
            this._var.asset = asset;
            templateSelector.assetId = asset.Id;
            const footerButtons = popup.container.querySelectorAll('.ui-popup-footer>.ui-popup-button');
            footerButtons[0].style.display = 'none';
        }
        else
            this._changePage(0);
        popup.rect = { width: 1220 };
        const mask = await popup.show();
        assetSelector.init();
        return mask;
    }

    show(asset) {
        if (this._var.popup == null) {
            return this.create(asset);
        }
        if (asset) {
            this._var.asset = asset;
            this._var.template = null;
            this._changePage(1);
            this._var.templateSelector._var.el.inputSearch.value = '';
            this._var.templateSelector.assetId = asset.Id;
            const footerButtons = this._var.popup.container.querySelectorAll('.ui-popup-footer>.ui-popup-button');
            footerButtons[0].style.display = 'none';
        }
        else {
            this._changePage(0);
            const selector = this._var.assetSelector;
            selector._var.el.inputSearch.value = '';
            selector._var.el.dropAssetGroup.select('-1');
            selector._var.el.dropJobsite.select('-1');
            selector._var.el.dropJobsiteCode.select('-1');
            selector.refresh();
        }
        return this._var.popup.show();
    }

    _select() {
        if (typeof this.onSelected === 'function') {
            this.onSelected(this._var.asset, this._var.template);
        }
    }

    _changePage(index) {
        if (isNaN(index) || index < 0 || index >= 2) {
            return;
        }
        this._var.index = index;
        this._var.containers[0].style.display = index === 0 ? '' : 'none';
        this._var.containers[1].style.display = index === 1 ? '' : 'none';
        const footerButtons = this._var.popup.container.querySelectorAll('.ui-popup-footer>.ui-popup-button');
        footerButtons[0].style.display = index === 0 ? 'none' : '';
        footerButtons[1].style.display = index === 1 ? 'none' : '';
        footerButtons[2].style.display = index === 0 ? 'none' : '';
    }
}