import { __decorate } from "tslib";
import { html } from "lit";
import { property, queryAssignedElements } from "lit/decorators.js";
import { UiElement } from "../UiElement.js";
/**
 * @fires select - When button's selection change.
 */
export default class SegmentedButtonsSet extends UiElement {
    constructor() {
        super();
        this.disabled = false;
        /**
         * Whether multiple buttons can be selected at once.
         * @attribute
         */
        this.multiselect = false;
        this.addEventListener('trigger', this.handleButtonTrigger.bind(this));
    }
    connectedCallback() {
        super.connectedCallback();
        this.setAttribute('role', 'group');
    }
    isButtonDisabled(index) {
        if (this.isOutOfBounds(index))
            return false;
        return this.buttons[index].disabled;
    }
    setButtonDisabled(index, disabled) {
        if (this.isOutOfBounds(index))
            return;
        this.buttons[index].disabled = disabled;
    }
    isButtonSelected(index) {
        if (this.isOutOfBounds(index))
            return false;
        return this.buttons[index].selected;
    }
    setButtonSelected(index, selected) {
        // Ignore out-of-index values.
        if (this.isOutOfBounds(index))
            return;
        // Ignore disabled buttons.
        if (this.isButtonDisabled(index))
            return;
        if (this.multiselect) {
            this.buttons[index].selected = selected;
            this.dispatchSelected(index);
            return;
        }
        // Single-select segmented buttons are not unselectable.
        if (!selected)
            return;
        this.buttons[index].selected = true;
        this.dispatchSelected(index);
        // Deselect all other buttons for single-select.
        for (let i = 0; i < this.buttons.length; i++) {
            if (i === index)
                continue;
            this.buttons[i].selected = false;
        }
    }
    handleButtonTrigger(e) {
        const index = this.buttons.indexOf(e.target);
        this.toggleSelection(index);
    }
    toggleSelection(index) {
        this.setButtonSelected(index, !this.buttons[index].selected);
    }
    isOutOfBounds(index) {
        return index < 0 || index >= this.buttons.length;
    }
    dispatchSelected(index) {
        this.dispatchEvent(new CustomEvent('select', {
            detail: {
                button: this.buttons[index],
                selected: this.buttons[index].selected,
                index,
            },
            bubbles: true,
            composed: true
        }));
    }
    render() {
        return html `<slot></slot>`;
    }
}
__decorate([
    property({ type: Boolean })
], SegmentedButtonsSet.prototype, "multiselect", void 0);
__decorate([
    queryAssignedElements({ flatten: true })
], SegmentedButtonsSet.prototype, "buttons", void 0);
//# sourceMappingURL=SegmentedButtonsSet.js.map