import { Host, h } from "@stencil/core";
import { cls, getId, isEmpty } from "../../utils/helpers";
import { Lang } from "../../services/lang";
export class XSelector {
    constructor() {
        /**
         * Element ID for internal reference
         */
        this.inputId = getId('input');
        this.label = undefined;
        this.name = undefined;
        this.info = undefined;
        this.flex = undefined;
        this.required = undefined;
        this.loading = undefined;
        this.multiple = undefined;
        this.unselectable = undefined;
        this.value = '';
        this.isValid = true;
        this.isFocused = undefined;
        this.isLoading = undefined;
        this.isDisabled = undefined;
    }
    /**
     * Element listen for child element changes
     */
    handleChanged() {
        this.getValues();
        this.formValidateCallback(true);
    }
    /**
     * Watch changes in value property
     */
    watchValue() {
        var _a;
        this.updateValue();
        this.el.dispatchEvent(new InputEvent('input', { bubbles: false }));
        this.formValidateCallback(this.isReady);
        (_a = this.internals.form) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new InputEvent('input', { bubbles: false }));
        if (!this.isReady) {
            this.isReady = true;
        }
    }
    /**
     * This is called when the 'disabled' attribute of the element or or an ancestor <fieldset> is updated
     *
     * @param disabled
     */
    formDisabledCallback(disabled) {
        this.isDisabled = disabled;
    }
    /**
     * This is called when the parent/owner form is reset
     */
    formResetCallback() {
        this.isValid = true;
        this.internals.setFormValue('');
        this.value = this.multiple ? [] : '';
    }
    /**
     * This is called when the input is validated
     */
    formValidateCallback(dispatchValidation) {
        if (this.required && isEmpty(this.value)) {
            this.internals.setValidity({ valueMissing: true }, Lang.get('fields.validation.value-missing'));
        }
        else {
            this.internals.setValidity({});
        }
        if (dispatchValidation) {
            this.isValid = this.internals.validity.valid;
            this.onValidateInputEvent.emit(this.internals);
        }
    }
    /**
     * This is called on component before load
     */
    componentWillLoad() {
        if (isEmpty(this.value)) {
            this.getValues();
        }
        this.updateValue();
    }
    /**
     * This called on input field is unfocused
     */
    onBlurInput() {
        this.isFocused = false;
        setTimeout(() => this.formValidateCallback(true), 50);
    }
    /**
     * This called on input field is focused
     */
    onFocusInput() {
        this.isFocused = true;
    }
    /**
     * Get the selected values from child elements
     */
    getValues() {
        var _a, _b;
        let value = this.multiple ? [] : '';
        const elements = this.el.querySelectorAll('x-selector-item, x-selector-tag');
        if (Array.isArray(value)) {
            value = Array.from(elements).filter(el => el.selected).map(el => el.value);
        }
        else {
            value = (_b = (_a = Array.from(elements).find(el => el.selected)) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : null;
        }
        this.value = value;
    }
    /**
     * Update the selected values from child elements
     */
    updateValue() {
        var _a;
        const elements = Array.from(this.el.children)
            .filter(el => ['x-selector-item', 'x-selector-tag'].includes(el.nodeName.toLowerCase()))
            .map(el => el.nodeName.toLowerCase() === 'x-selector-tag' ?
            el :
            el);
        elements.forEach((element) => {
            if (this.multiple) {
                element.selected = this.value.includes(element.value);
            }
            else {
                element.selected = this.value === element.value;
            }
        });
        if (this.multiple && Array.isArray(this.value)) {
            if (!((_a = this.name) === null || _a === void 0 ? void 0 : _a.length)) {
                return;
            }
            const data = new FormData();
            this.value.forEach(value => {
                data.append(this.name, value);
            });
            this.internals.setFormValue(data);
        }
        if (!this.multiple && typeof this.value === 'string') {
            this.internals.setFormValue(this.value || null);
        }
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: 'a894eb80a17d830709d3293cea3a85ee83120db6', class: cls({ 'flex': this.flex }), tabindex: "-1", onFocus: () => this.onFocusInput(), onBlur: () => this.onBlurInput(), id: this.inputId, required: this.required }, h("slot", { key: '95f218d283a60b5194fc5a99da9e0025ea2b814a' }));
    }
    static get is() { return "x-selector"; }
    static get formAssociated() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input label text"
                },
                "attribute": "label",
                "reflect": false
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input name for forms keys"
                },
                "attribute": "name",
                "reflect": false
            },
            "info": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input information block"
                },
                "attribute": "info",
                "reflect": false
            },
            "flex": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input flex style for block selector items"
                },
                "attribute": "flex",
                "reflect": false
            },
            "required": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input required for forms validations"
                },
                "attribute": "required",
                "reflect": false
            },
            "loading": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element show loading and block for edit"
                },
                "attribute": "loading",
                "reflect": false
            },
            "multiple": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element multiple choises selector"
                },
                "attribute": "multiple",
                "reflect": false
            },
            "unselectable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input unselectable"
                },
                "attribute": "unselectable",
                "reflect": false
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "Array<string> | string | null",
                    "resolved": "string | string[]",
                    "references": {
                        "Array": {
                            "location": "global",
                            "id": "global::Array"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input value"
                },
                "attribute": "value",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "isValid": {},
            "isFocused": {},
            "isLoading": {},
            "isDisabled": {}
        };
    }
    static get events() {
        return [{
                "method": "onValidateInputEvent",
                "name": "validated",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On validate input event"
                },
                "complexType": {
                    "original": "ElementInternals",
                    "resolved": "ElementInternals",
                    "references": {
                        "ElementInternals": {
                            "location": "global",
                            "id": "global::ElementInternals"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "watchValue"
            }];
    }
    static get listeners() {
        return [{
                "name": "changed",
                "method": "handleChanged",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
    static get attachInternalsMemberName() { return "internals"; }
}
