/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, forceUpdate, h } from "@stencil/core";
import cn from "../../global/lib/cn";
import { getInputLocalization } from "../../features/form-hook/index";
import { FormInputLabel } from "./components/form-input-label";
import { FormErrorMessage } from "./components/form-error-message";
import { getNestedValue } from "../../global/lib/get-nested-value";
export class FormSelect {
    constructor() {
        this.language = 'en';
        this.reverseOptions = false;
        this.forceOpenUpwards = false;
        this.clearable = false;
        this.localization = {};
        this.searchValue = '';
        this.isOpen = false;
        this.selectedValue = '';
        this.options = [];
        this.fetchingErrorMessage = null;
        this.handleSelection = (option) => {
            this.selectedValue = option.value;
            this.searchValue = option.label;
            this.isOpen = false;
        };
        this.reset = (newValue = '') => {
            const defaultOption = this.options.find(opt => opt.value === newValue || opt.value === this.defaultValue) || { value: newValue, label: '' };
            this.handleSelection(defaultOption);
        };
        this.updateShiftSelectContext = (newValues) => {
            Object.entries(newValues).forEach(([key, value]) => {
                this[key] = value;
            });
        };
    }
    async changeLanguage() {
        this.fetch();
    }
    async fetchListener() {
        this.fetch();
    }
    async resetListener() {
        this.reset();
    }
    async componentWillLoad() {
        this.form.subscribe(this.name, this);
        if (this.staticValue) {
            this.defaultValue = this.staticValue.value;
            this.clearable = false;
        }
    }
    async disconnectedCallback() {
        var _a;
        (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
        this.form.unsubscribe(this.name);
    }
    async fetch() {
        var _a, _b, _c, _d;
        try {
            this.isFetching = true;
            if (this.abortController)
                this.abortController.abort();
            let options;
            if (!!this.staticValue) {
                const localizedStaticValue = this.staticValue[this.language];
                if (localizedStaticValue && (localizedStaticValue === null || localizedStaticValue === void 0 ? void 0 : localizedStaticValue.value) && (localizedStaticValue === null || localizedStaticValue === void 0 ? void 0 : localizedStaticValue.label))
                    options = [localizedStaticValue];
                else
                    options = [this.staticValue];
            }
            else {
                this.abortController = new AbortController();
                options = await this.fetcher({ language: this.language, signal: this.abortController.signal, locale: this.form.getFormLocale()[0], context: this });
            }
            if (((_a = this.form) === null || _a === void 0 ? void 0 : _a.formStructure) || ((_b = this.form) === null || _b === void 0 ? void 0 : _b.context))
                forceUpdate(((_c = this.form) === null || _c === void 0 ? void 0 : _c.formStructure) || ((_d = this.form) === null || _d === void 0 ? void 0 : _d.context));
            this.form.context[this.name + 'List'] = options;
            this.fetchingErrorMessage = null;
            this.options = options;
            if (this.defaultValue) {
                const defaultOption = options.find(option => option.value === this.defaultValue);
                if (defaultOption)
                    this.handleSelection(defaultOption);
            }
        }
        catch (error) {
            if (error && (error === null || error === void 0 ? void 0 : error.name) === 'AbortError')
                return;
            console.error(error);
            this.options = [];
            this.fetchingErrorMessage = (error === null || error === void 0 ? void 0 : error.message) || null;
        }
        finally {
            this.isFetching = false;
        }
    }
    async componentDidLoad() {
        this.fetch();
    }
    render() {
        var _a, _b, _c;
        const { disabled, isRequired, meta, isError, errorMessage } = this.form.getInputState(this.name);
        const [locale] = this.form.getFormLocale();
        const { label, placeholder, errorTextMessage } = getInputLocalization(this, meta, errorMessage);
        const selectedItem = this.options.find(item => this.selectedValue === item.value);
        if (!selectedItem) {
            this.selectedValue = '';
        }
        const filteredOptions = selectedItem ? this.options : this.options.filter(option => { var _a, _b; return (_a = option === null || option === void 0 ? void 0 : option.label) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes((_b = this.searchValue) === null || _b === void 0 ? void 0 : _b.toLowerCase()); });
        const disableInput = disabled || this.isDisabled || this.isLoading || !!this.staticValue;
        if (this.isHidden)
            return (h(Host, { translate: "no", style: { display: this.isHidden ? 'none' : 'block' } }, h("form-shadow-input", { name: this.name, form: this.form, value: this.selectedValue })));
        return (h(Host, { translate: "no" }, h("label", { part: `${this.name}`, id: this.wrapperId, class: cn('form-input-label-container', this.wrapperClass, { disabled: disableInput }) }, h(FormInputLabel, { name: this.name, isRequired: isRequired || this.isRequired, label: label }), h("shift-select", { name: this.name, isError: isError, isOpen: this.isOpen, options: filteredOptions, clearable: this.clearable, isLoading: this.isFetching, disableInput: disableInput, searchable: this.searchable, searchValue: this.searchValue, selectedValue: this.selectedValue, reverseOptions: this.reverseOptions, handleSelection: this.handleSelection, forceOpenUpwards: this.forceOpenUpwards, updateContext: this.updateShiftSelectContext, direction: locale.sharedFormLocales.direction, placeholder: placeholder || (meta === null || meta === void 0 ? void 0 : meta.placeholder), noSelectionText: (_a = locale === null || locale === void 0 ? void 0 : locale.sharedFormLocales) === null || _a === void 0 ? void 0 : _a.noSelectOptions, fetchingErrorText: !this.fetchingErrorMessage ? '' : getNestedValue(locale, this.fetchingErrorMessage) || this.fetchingErrorMessage || ((_c = (_b = locale === null || locale === void 0 ? void 0 : locale.sharedFormLocales) === null || _b === void 0 ? void 0 : _b.errors) === null || _c === void 0 ? void 0 : _c.wildCard) }, h("form-shadow-input", { name: this.name, form: this.form, value: this.selectedValue })), h(FormErrorMessage, { name: this.name, isError: isError, errorMessage: errorTextMessage }))));
    }
    static get is() { return "form-select"; }
    static get originalStyleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "attribute": "name",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "resetKey": {
                "type": "any",
                "attribute": "reset-key",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "fetcherKey": {
                "type": "any",
                "attribute": "fetcher-key",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperId": {
                "type": "string",
                "attribute": "wrapper-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isHidden": {
                "type": "boolean",
                "attribute": "is-hidden",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isLoading": {
                "type": "boolean",
                "attribute": "is-loading",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "form": {
                "type": "unknown",
                "attribute": "form",
                "mutable": false,
                "complexType": {
                    "original": "FormHook<any>",
                    "resolved": "FormHook<any>",
                    "references": {
                        "FormHook": {
                            "location": "import",
                            "path": "~features/form-hook/form-hook",
                            "id": "src/features/form-hook/form-hook.ts::FormHook"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "searchable": {
                "type": "boolean",
                "attribute": "searchable",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isRequired": {
                "type": "boolean",
                "attribute": "is-required",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDisabled": {
                "type": "boolean",
                "attribute": "is-disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperClass": {
                "type": "string",
                "attribute": "wrapper-class",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "fetcher": {
                "type": "unknown",
                "attribute": "fetcher",
                "mutable": false,
                "complexType": {
                    "original": "FormSelectFetcher",
                    "resolved": "(props: FormSelectFetcherProps) => Promise<FormSelectItem[]>",
                    "references": {
                        "FormSelectFetcher": {
                            "location": "import",
                            "path": "~features/form-hook/",
                            "id": "src/features/form-hook/index.ts::FormSelectFetcher"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "staticValue": {
                "type": "unknown",
                "attribute": "static-value",
                "mutable": false,
                "complexType": {
                    "original": "FormSelectItem",
                    "resolved": "{ value: string; label: string; meta?: Record<string, string>; }",
                    "references": {
                        "FormSelectItem": {
                            "location": "import",
                            "path": "~features/form-hook/",
                            "id": "src/features/form-hook/index.ts::FormSelectItem"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": false,
                "complexType": {
                    "original": "LanguageKeys",
                    "resolved": "\"ar\" | \"en\" | \"ku\" | \"ru\"",
                    "references": {
                        "LanguageKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::LanguageKeys"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'en'"
            },
            "reverseOptions": {
                "type": "boolean",
                "attribute": "reverse-options",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "forceOpenUpwards": {
                "type": "boolean",
                "attribute": "force-open-upwards",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "clearable": {
                "type": "boolean",
                "attribute": "clearable",
                "mutable": true,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "defaultValue": {
                "type": "string",
                "attribute": "default-value",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "localization": {
                "type": "unknown",
                "attribute": "localization",
                "mutable": false,
                "complexType": {
                    "original": "FormInputLocalization",
                    "resolved": "{ [lang: string]: { label?: string; placeholder?: string; require?: string; format?: string; minMessage: string; maxMessage: string; betweenMessage: string; }; }",
                    "references": {
                        "FormInputLocalization": {
                            "location": "import",
                            "path": "~features/form-hook/",
                            "id": "src/features/form-hook/index.ts::FormInputLocalization"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            }
        };
    }
    static get states() {
        return {
            "searchValue": {},
            "isOpen": {},
            "selectedValue": {},
            "isFetching": {},
            "options": {},
            "fetchingErrorMessage": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "changeLanguage"
            }, {
                "propName": "fetcherKey",
                "methodName": "fetchListener"
            }, {
                "propName": "resetKey",
                "methodName": "resetListener"
            }];
    }
}
