import { __decorate, __metadata } from "tslib";
import { h, Host, } from "@stencil/core";
import { ariaBooleanToString } from "../../../utils/aria";
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 RadioGroup {
    constructor() {
        this.inputId = `bal-rg-${radioGroupIds++}`;
        this.inheritedAttributes = {};
        this.ariaForm = defaultBalAriaForm;
        /**
         * Defines the layout of the radio button
         */
        this.interface = undefined;
        /**
         * If `true`, the radios can be deselected.
         */
        this.allowEmptySelection = 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 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.disabled = undefined;
        /**
         * If `true` the element can not mutated, meaning the user can not edit the control.
         */
        this.readonly = undefined;
        /**
         * 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;
        this.onOptionChange = async () => {
            this.setRadioTabindex(this.value);
            this.setRadioChecked();
        };
        /**
         * PRIVATE METHODS
         * ------------------------------------------------------
         */
        this.setRadioTabindex = (value) => {
            const radios = this.getRadios();
            // Get the first radio that is not disabled and the checked one
            const first = radios.find(radio => !radio.disabled);
            const checked = radios.find(radio => radio.value === value && !radio.disabled);
            if (!first && !checked) {
                return;
            }
            // If an enabled checked radio exists, set it to be the focusable radio
            // otherwise we default to focus the first radio
            const focusable = checked || first;
            for (const radio of radios) {
                const tabindex = radio === focusable ? 0 : -1;
                radio.setButtonTabindex(tabindex);
            }
        };
        /**
         * EVENT BINDING
         * ------------------------------------------------------
         */
        this.onClick = (ev) => {
            const element = ev.target;
            if (element.href) {
                return;
            }
            ev.preventDefault();
            const selectedRadio = ev.target && ev.target.closest('bal-radio');
            if (selectedRadio && !selectedRadio.disabled && !selectedRadio.readonly) {
                const currentValue = this.value;
                const newValue = selectedRadio.value;
                if (newValue !== currentValue) {
                    this.value = newValue;
                }
                else if (this.allowEmptySelection) {
                    this.value = undefined;
                }
                this.balChange.emit(this.value);
            }
        };
    }
    createLogger(log) {
        this.log = log;
    }
    async optionChanged() {
        this.onOptionChange();
        this.mutationObserverActive = this.options === undefined;
    }
    invalidChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.invalid = value;
            });
        }
    }
    disabledChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.disabled = value;
            });
        }
    }
    readonlyChanged(value) {
        if (value !== undefined) {
            this.getRadios().forEach(radio => {
                radio.readonly = value;
            });
        }
    }
    valueChanged() {
        this.onOptionChange();
    }
    columnsChanged(value) {
        this.getRadios().forEach(radio => (radio.colSize = value));
    }
    columnsTabletChanged(value) {
        this.getRadios().forEach(radio => (radio.colSizeTablet = value));
    }
    columnsMobileChanged(value) {
        this.getRadios().forEach(radio => (radio.colSizeMobile = value));
    }
    /**
     * LIFECYCLE
     * ------------------------------------------------------
     */
    connectedCallback() {
        this.initialValue = this.value;
        this.mutationObserverActive = this.options === undefined;
    }
    componentWillLoad() {
        this.setRadioInterface();
        this.disabledChanged(this.disabled);
        this.readonlyChanged(this.readonly);
        this.invalidChanged(this.invalid);
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
        this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']);
    }
    focusInListener(ev) {
        this.balFocus.emit(ev);
    }
    focusOutListener(ev) {
        this.balBlur.emit(ev);
    }
    mutationListener() {
        this.setRadioInterface();
        this.disabledChanged(this.disabled);
        this.readonlyChanged(this.readonly);
        this.invalidChanged(this.invalid);
        this.columnsChanged(this.columns);
        this.columnsTabletChanged(this.columnsTablet);
        this.columnsMobileChanged(this.columnsMobile);
        this.onOptionChange();
    }
    listenOnClick(ev) {
        if (isDescendant(this.el, ev.target)) {
            stopEventBubbling(ev);
        }
    }
    radioFocusListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-radio')) {
            stopEventBubbling(ev);
        }
    }
    radioBlurListener(ev) {
        const { target } = ev;
        if (target && isDescendant(this.el, target) && hasTagName(target, 'bal-radio')) {
            stopEventBubbling(ev);
        }
    }
    resetListener(ev) {
        const formElement = ev.target;
        if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) {
            this.value = this.initialValue;
        }
    }
    onKeydown(ev) {
        if (ev.target && !this.el.contains(ev.target)) {
            return;
        }
        // Get all radios inside of the radio group and then
        // filter out disabled radios since we need to skip those
        const radios = this.getRadios().filter(radio => !radio.disabled);
        const targetRadio = ev.target.closest('bal-radio');
        // Only move the radio if the current focus is in the radio group
        if (targetRadio && radios.includes(targetRadio)) {
            const index = radios.findIndex(radio => radio === targetRadio);
            const current = radios[index];
            let next;
            // If hitting arrow down or arrow right, move to the next radio
            // If we're on the last radio, move to the first radio
            if (['ArrowDown', 'ArrowRight'].includes(ev.code)) {
                next = index === radios.length - 1 ? radios[0] : radios[index + 1];
            }
            // If hitting arrow up or arrow left, move to the previous radio
            // If we're on the first radio, move to the last radio
            if (['ArrowUp', 'ArrowLeft'].includes(ev.code)) {
                next = index === 0 ? radios[radios.length - 1] : radios[index - 1];
            }
            if (next && radios.includes(next)) {
                next.setFocus(ev);
                this.value = next.value;
                this.balChange.emit(this.value);
            }
            // Update the radio group value when a user presses the
            // space bar on top of a selected radio
            if (['Space'].includes(ev.code)) {
                this.value = this.allowEmptySelection && this.value !== undefined ? undefined : current.value;
                this.balChange.emit(this.value);
                // Prevent browsers from jumping
                // to the bottom of the screen
                ev.preventDefault();
            }
        }
    }
    /**
     * PUBLIC METHODS
     * ------------------------------------------------------
     */
    /** @internal */
    async setValue(value) {
        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);
    }
    setRadioInterface() {
        this.getRadios().forEach((radio) => {
            if (this.interface) {
                radio.interface = this.interface;
            }
        });
    }
    setRadioChecked() {
        this.getRadios().forEach((radio) => {
            if (radio.updateState) {
                radio.updateState();
            }
        });
    }
    /**
     * GETTERS
     * ------------------------------------------------------
     */
    getRadios() {
        return Array.from(this.el.querySelectorAll('bal-radio'));
    }
    /**
     * RENDER
     * ------------------------------------------------------
     */
    render() {
        const block = BEM.block('radio-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: "radiogroup", "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-disabled": ariaBooleanToString(this.disabled), 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-radio", { key: option.value, name: option.name || this.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-radio-group"; }
    static get originalStyleUrls() {
        return {
            "$": ["bal-radio-group.sass"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["bal-radio-group.css"]
        };
    }
    static get properties() {
        return {
            "options": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "BalRadioOption[]",
                    "resolved": "BalRadioOption[]",
                    "references": {
                        "BalRadioOption": {
                            "location": "import",
                            "path": "../bal-radio.type",
                            "id": "src/components/bal-radio/bal-radio.type.ts::BalRadioOption"
                        }
                    }
                },
                "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.BalRadioGroupInterface",
                    "resolved": "\"button\" | \"radio\" | \"tile\"",
                    "references": {
                        "BalProps": {
                            "location": "global",
                            "id": "global::BalProps"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Defines the layout of the radio button"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "interface",
                "defaultValue": "undefined"
            },
            "allowEmptySelection": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If `true`, the radios can be deselected."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "allow-empty-selection",
                "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 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": "disabled",
                "defaultValue": "undefined"
            },
            "readonly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "If `true` the element can not mutated, meaning the user can not edit the control."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "readonly",
                "defaultValue": "undefined"
            },
            "value": {
                "type": "any",
                "mutable": true,
                "complexType": {
                    "original": "any | null",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "the value of the radio group."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            },
            "columns": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "BalProps.BalRadioGroupColumns",
                    "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.BalRadioGroupColumns",
                    "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.BalRadioGroupColumns",
                    "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.BalRadioGroupChangeDetail",
                    "resolved": "boolean | number | string",
                    "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.BalRadioGroupFocusDetail",
                    "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.BalRadioGroupBlurDetail",
                    "resolved": "FocusEvent",
                    "references": {
                        "BalEvents": {
                            "location": "global",
                            "id": "global::BalEvents"
                        }
                    }
                }
            }];
    }
    static get methods() {
        return {
            "setValue": {
                "complexType": {
                    "signature": "(value: number | string | boolean) => Promise<void>",
                    "parameters": [{
                            "name": "value",
                            "type": "string | number | boolean",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": [{
                            "name": "internal",
                            "text": undefined
                        }]
                }
            },
            "getOptionByValue": {
                "complexType": {
                    "signature": "(value: string) => Promise<BalRadioOption>",
                    "parameters": [{
                            "name": "value",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "BalRadioOption": {
                            "location": "import",
                            "path": "../bal-radio.type",
                            "id": "src/components/bal-radio/bal-radio.type.ts::BalRadioOption"
                        }
                    },
                    "return": "Promise<BalRadioOption>"
                },
                "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": "listenOnClick",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "balFocus",
                "method": "radioFocusListener",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "balBlur",
                "method": "radioBlurListener",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "reset",
                "method": "resetListener",
                "target": "document",
                "capture": true,
                "passive": false
            }, {
                "name": "keydown",
                "method": "onKeydown",
                "target": "document",
                "capture": false,
                "passive": false
            }];
    }
}
__decorate([
    Logger('bal-radio-group'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "createLogger", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "focusInListener", null);
__decorate([
    ListenToFocus(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "focusOutListener", null);
__decorate([
    ListenToMutation({ tags: ['bal-radio-group', 'bal-radio'], attributes: false, characterData: false }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], RadioGroup.prototype, "mutationListener", null);
let radioGroupIds = 0;
