import { __decorate, __metadata } from "tslib";
import { h, Host, } from "@stencil/core";
import { ariaBooleanToString } from "../../../utils/aria";
import { areArraysEqual } from "../../../utils/array";
import { inheritAttributes } from "../../../utils/attributes";
import { BEM } from "../../../utils/bem";
import { ListenToFocus } from "../../../utils/focus";
import { defaultBalAriaForm } from "../../../utils/form";
import { stopEventBubbling } from "../../../utils/form-input";
import { hasTagName, isDescendant } from "../../../utils/helpers";
import { Logger } from "../../../utils/log";
import { ListenToMutation } from "../../../utils/mutation";
export class CheckboxGroup {
    constructor() {
        this.inputId = `bal-cg-${checkboxGroupIds++}`;
        this.inheritedAttributes = {};
        this.ariaForm = defaultBalAriaForm;
        /**
         * Defines the layout of the checkbox button
         */
        this.interface = undefined;
        /**
         * If `true` it acts as the main form control
         */
        this.control = false;
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.inputId;
        /**
         * Displays the checkboxes vertically
         */
        this.vertical = false;
        /**
         * If `true`, the controls will be vertically on mobile devices.
         */
        this.verticalOnMobile = false;
        /**
         * Uses the whole width
         */
        this.expanded = false;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.invalid = undefined;
        /**
         * If `true`, the user cannot interact with the checkboxes.
         */
        this.disabled = undefined;
        /**
         * If `true`, the user cannot interact with the checkboxes.
         */
        this.readonly = undefined;
        /**
         * The value of the control.
         */
        this.value = [];
        /**
         * Defines the column size like the grid.
         */
        this.columns = 1;
        /**
         * Defines the column size for tablet and bigger like the grid.
         */
        this.columnsTablet = 1;
        /**
         * Defines the column size for mobile and bigger like the grid.
         */
        this.columnsMobile = 1;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        /**
         * LISTENERS
         * ------------------------------------------------------
         */
        this.hasFocus = false;
        this.mutationObserverActive = true;
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        this.onClick = (ev) => {
            if (!this.control) {
                return;
            }
            const element = ev.target;
            if (element.href) {
                return;
            }
            const selectedCheckbox = ev.target && ev.target.closest('bal-checkbox');
            if (selectedCheckbox) {
                if (selectedCheckbox.disabled || selectedCheckbox.readonly) {
                    return ev.stopPropagation();
                }
            }
            this.updateValues();
        };
        this.onOptionChange = async () => {
            this.sync();
        };
    }
    createLogger(log) {
        this.log = log;
    }
    async optionChanged() {
        if (this.control) {
            this.onOptionChange();
            this.mutationObserverActive = this.options === undefined;
        }
    }
    invalidChanged(value) {
        if (this.control) {
            if (value !== undefined) {
                this.getCheckboxes().forEach(child => {
                    child.invalid = value;
                });
            }
        }
    }
    disabledChanged(value) {
        if (this.control) {
            if (value !== undefined) {
                this.getCheckboxes().forEach(child => {
                    child.disabled = value;
                });
            }
        }
    }
    readonlyChanged(value) {
        if (this.control) {
            if (value !== undefined) {
                this.getCheckboxes().forEach(child => {
                    child.readonly = value;
                });
            }
        }
    }
    valueChanged(_value, oldValue) {
        if (this.control) {
            if (!areArraysEqual(this.value, oldValue)) {
                this.onOptionChange();
            }
        }
        else {
            this.onOptionChange();
        }
    }
    columnsChanged(value) {
        this.getCheckboxes().forEach(checkbox => (checkbox.colSize = value));
    }
    columnsTabletChanged(value) {
        this.getCheckboxes().forEach(checkbox => (checkbox.colSizeTablet = value));
    }
    columnsMobileChanged(value) {
        this.getCheckboxes().forEach(checkbox => (checkbox.colSizeMobile = value));
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        if (this.control) {
            this.mutationObserverActive = this.options === undefined;
            this.valueChanged(this.value, []);
        }
    }
    componentWillLoad() {
        if (this.control) {
            this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']);
            this.disabledChanged(this.disabled);
            this.invalidChanged(this.invalid);
            this.readonlyChanged(this.readonly);
        }
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
    }
    focusInListener(ev) {
        this.balFocus.emit(ev);
    }
    focusOutListener(ev) {
        this.balBlur.emit(ev);
    }
    mutationListener() {
        if (this.control) {
            this.disabledChanged(this.disabled);
            this.readonlyChanged(this.readonly);
        }
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
    }
    listenOnCheckboxChange(ev) {
        if (this.control) {
            if (isDescendant(this.el, ev.target)) {
                stopEventBubbling(ev);
                this.updateValues();
            }
        }
    }
    resetHandler(ev) {
        const formElement = ev.target;
        if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) {
            if (this.control) {
                this.value = [];
            }
            this.onOptionChange();
        }
    }
    checkboxFocusListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-checkbox')) {
            stopEventBubbling(ev);
        }
    }
    checkboxBlurListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-checkbox')) {
            stopEventBubbling(ev);
        }
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /** @internal */
    async setValue(value) {
        if (this.control) {
            this.value = value;
        }
    }
    /**
     * Find the options properties by its value
     */
    async getOptionByValue(value) {
        const options = this.options;
        if (options) {
            return options.find(option => option.value === value);
        }
        return undefined;
    }
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    /**
     * PRIVATE METHODS
     * ------------------------------------------------------
     */
    sync() {
        if (this.control) {
            const isChecked = (checkbox) => {
                for (let index = 0; index < this.value.length; index++) {
                    const valueItem = this.value[index];
                    if (valueItem !== undefined && valueItem.toString() === checkbox.value.toString()) {
                        return true;
                    }
                }
                return false;
            };
            this.getCheckboxes().forEach((checkbox) => {
                checkbox.checked = isChecked(checkbox);
            });
        }
        this.getCheckboxes().forEach((checkbox) => {
            if (this.interface) {
                checkbox.interface = this.interface;
            }
        });
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    getCheckboxes() {
        return Array.from(this.el.querySelectorAll('bal-checkbox'));
    }
    updateValues() {
        // generate new value array out of the checked checkboxes
        const newValue = [];
        this.getCheckboxes().forEach(cb => {
            if (cb.checked) {
                newValue.push(cb.value);
            }
        });
        if (!areArraysEqual(this.value, newValue)) {
            this.value = [...newValue];
            this.balChange.emit(this.value);
        }
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = BEM.block('checkbox-group');
        const innerEl = block.element('inner');
        const rawOptions = this.options || [];
        const options = rawOptions.map(option => {
            if (typeof option.html === 'function') {
                return Object.assign(Object.assign({}, option), { html: option.html() });
            }
            return option;
        });
        return (h(Host, Object.assign({ class: Object.assign({}, block.class()), role: "group", "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-disabled": ariaBooleanToString(this.disabled), "aria-invalid": ariaBooleanToString(this.invalid), onClick: this.onClick }, this.inheritedAttributes), h("div", { class: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, innerEl.class()), innerEl.modifier('vertical-mobile').class(this.verticalOnMobile)), innerEl.modifier('vertical').class(this.vertical)), innerEl.modifier('expanded').class(this.expanded)), innerEl.modifier('button').class(this.interface === 'button')) }, h("slot", null), options.map(option => (h("bal-checkbox", { key: option.value, name: option.name, value: option.value, labelHidden: option.labelHidden, flat: option.flat, interface: option.interface, disabled: option.disabled, readonly: option.readonly, required: option.required, nonSubmit: !!option.nonSubmit, invalid: option.invalid, innerHTML: option.html }))))));
    }
    static get is() { return "bal-checkbox-group"; }
    static get originalStyleUrls() {
        return {
            "$": ["bal-checkbox-group.sass"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["bal-checkbox-group.css"]
        };
    }
    static get properties() {
        return {
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "BalCheckboxOption[]",
                    "resolved": "BalCheckboxOption[]",
                    "references": {
                        "BalCheckboxOption": {
                            "location": "import",
                            "path": "../bal-checkbox.type",
                            "id": "src/components/bal-checkbox/bal-checkbox.type.ts::BalCheckboxOption"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Steps can be passed as a property or through HTML markup."
                },
                "getter": false,
                "setter": false
            },
            "interface": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalCheckboxGroupInterface",
                    "resolved": "\"button\" | \"checkbox\" | \"switch\" | \"tile\"",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Defines the layout of the checkbox button"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "interface",
                "defaultValue": "undefined"
            },
            "control": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true` it acts as the main form control"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "control",
                "defaultValue": "false"
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The name of the control, which is submitted with the form data."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "name",
                "defaultValue": "this.inputId"
            },
            "vertical": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Displays the checkboxes vertically"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "vertical",
                "defaultValue": "false"
            },
            "verticalOnMobile": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the controls will be vertically on mobile devices."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "vertical-on-mobile",
                "defaultValue": "false"
            },
            "expanded": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Uses the whole width"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "expanded",
                "defaultValue": "false"
            },
            "invalid": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "invalid",
                "defaultValue": "undefined"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the user cannot interact with the checkboxes."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "disabled",
                "defaultValue": "undefined"
            },
            "readonly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the user cannot interact with the checkboxes."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "readonly",
                "defaultValue": "undefined"
            },
            "value": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "any[]",
                    "resolved": "any[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The value of the control."
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "columns": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalCheckboxGroupColumns",
                    "resolved": "1 | 2 | 3 | 4",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Defines the column size like the grid."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "columns",
                "defaultValue": "1"
            },
            "columnsTablet": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalCheckboxGroupColumns",
                    "resolved": "1 | 2 | 3 | 4",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Defines the column size for tablet and bigger like the grid."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "columns-tablet",
                "defaultValue": "1"
            },
            "columnsMobile": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalCheckboxGroupColumns",
                    "resolved": "1 | 2 | 3 | 4",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Defines the column size for mobile and bigger like the grid."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "columns-mobile",
                "defaultValue": "1"
            },
            "autoInvalidOff": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, in Angular reactive forms the control will not be set invalid"
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "auto-invalid-off",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "ariaForm": {}
        };
    }
    static get events() {
        return [{
                "method": "balChange",
                "name": "balChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the checked property has changed."
                },
                "complexType": {
                    "original": "BalEvents.BalCheckboxGroupChangeDetail",
                    "resolved": "any[]",
                    "references": {
                        "BalEvents": {
                            "location": "global",
                            "id": "global::BalEvents"
                        }
                    }
                }
            }, {
                "method": "balFocus",
                "name": "balFocus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the toggle has focus."
                },
                "complexType": {
                    "original": "BalEvents.BalCheckboxGroupFocusDetail",
                    "resolved": "FocusEvent",
                    "references": {
                        "BalEvents": {
                            "location": "global",
                            "id": "global::BalEvents"
                        }
                    }
                }
            }, {
                "method": "balBlur",
                "name": "balBlur",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Emitted when the toggle loses focus."
                },
                "complexType": {
                    "original": "BalEvents.BalCheckboxGroupBlurDetail",
                    "resolved": "FocusEvent",
                    "references": {
                        "BalEvents": {
                            "location": "global",
                            "id": "global::BalEvents"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "setValue": {
                "complexType": {
                    "signature": "(value: any[]) => Promise<void>",
                    "parameters": [{
                            "name": "value",
                            "type": "any[]",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": [{
                            "name": "internal",
                            "text": undefined
                        }]
                }
            },
            "getOptionByValue": {
                "complexType": {
                    "signature": "(value: string) => Promise<BalCheckboxOption>",
                    "parameters": [{
                            "name": "value",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "BalCheckboxOption": {
                            "location": "import",
                            "path": "../bal-checkbox.type",
                            "id": "src/components/bal-checkbox/bal-checkbox.type.ts::BalCheckboxOption"
                        }
                    },
                    "return": "Promise<BalCheckboxOption>"
                },
                "docs": {
                    "text": "Find the options properties by its value",
                    "tags": []
                }
            },
            "setAriaForm": {
                "complexType": {
                    "signature": "(ariaForm: BalAriaForm) => Promise<void>",
                    "parameters": [{
                            "name": "ariaForm",
                            "type": "BalAriaForm",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "BalAriaForm": {
                            "location": "import",
                            "path": "../../../utils/form",
                            "id": "src/utils/form.ts::BalAriaForm"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": [{
                            "name": "internal",
                            "text": undefined
                        }]
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "options",
                "methodName": "optionChanged"
            }, {
                "propName": "invalid",
                "methodName": "invalidChanged"
            }, {
                "propName": "disabled",
                "methodName": "disabledChanged"
            }, {
                "propName": "readonly",
                "methodName": "readonlyChanged"
            }, {
                "propName": "value",
                "methodName": "valueChanged"
            }, {
                "propName": "columns",
                "methodName": "columnsChanged"
            }, {
                "propName": "columnsTablet",
                "methodName": "columnsTabletChanged"
            }, {
                "propName": "columnsMobile",
                "methodName": "columnsMobileChanged"
            }];
    }
    static get listeners() {
        return [{
                "name": "balChange",
                "method": "listenOnCheckboxChange",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "reset",
                "method": "resetHandler",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "balFocus",
                "method": "checkboxFocusListener",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "balBlur",
                "method": "checkboxBlurListener",
                "target": "document",
                "capture": true,
                "passive": false
            }];
    }
}
__decorate([
    Logger('bal-checkbox-group'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], CheckboxGroup.prototype, "createLogger", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CheckboxGroup.prototype, "focusInListener", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], CheckboxGroup.prototype, "focusOutListener", null);
__decorate([
    ListenToMutation({ tags: ['bal-checkbox-group', 'bal-checkbox'], attributes: false, characterData: false }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], CheckboxGroup.prototype, "mutationListener", null);
let checkboxGroupIds = 0;
