import { h, Host } from "@stencil/core";
export class BceElementCheckbox {
    constructor() {
        this.options = [];
        this.handleOption = (event) => {
            var _a;
            if (!this.template)
                return;
            event.cancelBubble = true;
            const input = event.target;
            const value = (input.value || []);
            const query = this.el.shadowRoot.querySelector('bce-option bce-input');
            const otherEl = query;
            const last = this.template.options.length - 1;
            const oldValues = (_a = this.value) === null || _a === void 0 ? void 0 : _a.find(value => value.index === last);
            const newValues = value.indexOf('' + last) >= 0;
            const hasIndex = !oldValues && newValues;
            if (this.template.other && hasIndex)
                otherEl.shadowRoot.querySelector('input').focus();
            this.value = value
                .map(value => {
                const index = parseInt(value, 10);
                const text = otherEl && index === this.template.options.length - 1
                    ? otherEl.value
                    : this.template.options[index].text;
                return { index, text };
            })
                .sort((a, b) => a.index - b.index);
            // const index = -1;
            // if (otherEl && index === this.template!.options.length - 1)
            this.el.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
        };
        this.handleInput = (event) => {
            event.cancelBubble = true;
        };
    }
    generateOptions() {
        const options = this.handler
            .t('options')
            .map((option, index) => ({ option, index }));
        if (this.shuffle) {
            for (let i = options.length - 1; i > 0; i--) {
                let j = Math.floor(Math.random() * (i + 1));
                [options[i], options[j]] = [options[j], options[i]];
            }
        }
        this.options = options;
    }
    async validate(silent = false) {
        const root = this.el.shadowRoot;
        const query = root.querySelectorAll('bce-input, bce-select');
        const inputs = Array.from(query);
        const errors = await Promise.all(inputs.map(el => el.validate(silent)));
        return [].concat(...errors);
    }
    componentWillLoad() {
        this.generateOptions();
    }
    renderOther(option, index) {
        const value = this.value && this.value[this.value.length - 1];
        const isInput = value && value.index === index;
        const text = isInput ? value && value.text : '';
        const validation = isInput ? 'required' : '';
        return (h("bce-input", { disabled: this.disabled, placeholder: option.text, validation: validation, value: text || '', onInput: this.handleInput }));
    }
    renderOption(option, index) {
        if (!this.template)
            return null;
        const other = this.template.other && index === this.template.options.length - 1;
        return (h("bce-option", { value: '' + index }, other ? this.renderOther(option, index) : option.text));
    }
    render() {
        if (!this.template)
            return null;
        const validation = this.template.required
            ? ['required', this.template.validation].filter(v => !!v).join('|')
            : this.template.validation;
        return (h(Host, { orientation: this.template.orientation },
            h("p", null, this.handler.t('question')),
            h("bce-select", { disabled: this.disabled, type: "checkbox", value: this.value && this.value.map(value => value.index + ''), validation: validation, onInput: this.handleOption }, this.options.map(o => this.renderOption(o.option, o.index)))));
    }
    static get is() { return "bce-element-checkbox"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bce-element-checkbox.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["bce-element-checkbox.css"]
    }; }
    static get properties() { return {
        "disabled": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean | undefined",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "disabled",
            "reflect": true
        },
        "handler": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "InputHandler",
                "resolved": "InputHandler",
                "references": {
                    "InputHandler": {
                        "location": "import",
                        "path": "../../../utils/input-handler"
                    }
                }
            },
            "required": true,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            }
        },
        "language": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string | undefined",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "language",
            "reflect": false
        },
        "shuffle": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean | undefined",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "shuffle",
            "reflect": true
        },
        "template": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "CheckboxElement",
                "resolved": "CheckboxElement",
                "references": {
                    "CheckboxElement": {
                        "location": "import",
                        "path": "./element-checkbox"
                    }
                }
            },
            "required": true,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            }
        },
        "value": {
            "type": "unknown",
            "mutable": true,
            "complexType": {
                "original": "{ index: number; text: string }[]",
                "resolved": "undefined | { index: number; text: string; }[]",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": ""
            }
        }
    }; }
    static get states() { return {
        "options": {}
    }; }
    static get methods() { return {
        "validate": {
            "complexType": {
                "signature": "(silent?: boolean) => Promise<import(\"/Users/ngfk/Repositories/bce-module-editor/node_modules/@bcase/core/dist/types/index\").ValidatorError[]>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    },
                    "ValidatorError": {
                        "location": "global"
                    },
                    "HTMLBceInputElement": {
                        "location": "global"
                    },
                    "HTMLBceSelectElement": {
                        "location": "global"
                    },
                    "Inputs": {
                        "location": "global"
                    }
                },
                "return": "Promise<ValidatorError[]>"
            },
            "docs": {
                "text": "",
                "tags": []
            }
        }
    }; }
    static get elementRef() { return "el"; }
    static get watchers() { return [{
            "propName": "language",
            "methodName": "generateOptions"
        }, {
            "propName": "shuffle",
            "methodName": "generateOptions"
        }, {
            "propName": "template",
            "methodName": "generateOptions"
        }]; }
}
