// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Emit } from '../../../../Events/Decorators/EmitDecorator';
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Orientable } from '../../../Behaviors/Orientable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { CustomElement } from '../../Abstracts/CustomElement';
import { buttonGroupElementJoyStyle } from '../Button/Themes/ButtonGroupElement.Joy';
import { buttonGroupElementRetroStyle } from '../Button/Themes/ButtonGroupElement.Retro';
import { buttonGroupElementCosmopolitanStyle } from '../Button/Themes/ButtonGroupElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
import { Slottable } from '../../../Behaviors/Slottable';
import { toggleButtonGroupElementTemplate } from './ToggleButtonGroupElementTemplate';
import { ToggleButtonElement } from './ToggleButtonElement';
// #endregion
/**
 * Toggle Button Group - A container for grouping multiple toggle buttons with single-selection behavior.
 *
 * @element mosaik-toggle-button-group
 *
 * @description
 * Groups multiple Toggle Buttons to behave like a segmented control. Only one button can be selected at a time.
 * Inside a group, a toggle button cannot be deselected by clicking it again; clicking a selected button keeps it selected.
 *
 * @category Buttons
 * @fires toggleChanged - Called when the selection in the group changes.
 *
 * @public
 */
let ToggleButtonGroupElement = class ToggleButtonGroupElement extends Themeable(Invalidable(Disableable(Orientable(Valueable(Appearanceable(Variantable(Slottable(CustomElement)))))))) {
    // #region Fields
    _toggleChanged;
    _eventSubscriptions;
    _isSwitching;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._eventSubscriptions = [];
        this._toggleChanged = new HTMLElementEventEmitter(this, 'toggleChanged');
        this._isSwitching = false;
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-toggle-button-group';
    }
    /**
     * Called when the selection in the group changes.
     * Provides reference to `{@link IToggleButtonGroupChangedEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get toggleChanged() {
        return this._toggleChanged;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    onSlotChanges() {
        this.clearEvents();
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement);
        for (const [i, e] of elements.entries()) {
            e.disabled = this.disabled;
            e.appearance = this.appearance;
            e.variant = this.variant;
            e.dir = this.dir;
            e.isChecked = this.value === e.value;
            e.classList.add('button-group-button');
            e.classList.toggle('first', i === 0);
            e.classList.toggle('inner', i > 0 && i < elements.length - 1);
            e.classList.toggle('last', i === elements.length - 1);
            this._eventSubscriptions.push(e.on('checked', (evt) => this.onToggleChecked(evt), { passive: true }));
            this._eventSubscriptions.push(e.on('unchecked', (evt) => this.onToggleUnchecked(evt), { passive: true }));
        }
    }
    /**
     * Returns whether a form will validate when it is submitted, without having to submit it.
     *
     * @public
     * @override
     */
    checkValidity() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement)
            .filter((x) => x.isChecked);
        return elements.length > 0;
    }
    /**
     * Resets the element to its initial state.
     *
     * @public
     */
    reset() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement);
        elements.forEach((x) => x.uncheck());
        this.invalid = false;
    }
    /**
     * Emits the {@link toggleChanged} event.
     *
     * @protected
     */
    onToggleChanged(args) {
        const value = args.target.value;
        this._toggleChanged.emit({ value });
    }
    /**
     * @protected
     */
    onDisabledPropertyChange(_prev, next) {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement);
        if (next !== undefined) {
            elements.forEach((x) => x.disabled = next);
        }
    }
    /**
     * @protected
     */
    onAppearancePropertyChange(_prev, next) {
        if (next) {
            const elements = this.getSlotAssignments('')
                .filter((x) => x instanceof ToggleButtonElement);
            elements.forEach((x) => x.appearance = next);
        }
    }
    /**
     * @protected
     */
    onVariantPropertyChange(_prev, next) {
        if (next) {
            const elements = this.getSlotAssignments('')
                .filter((x) => x instanceof ToggleButtonElement);
            elements.forEach((x) => x.variant = next);
        }
    }
    /**
     * @protected
     */
    onDirPropertyChange(_prev, next) {
        if (next) {
            const elements = this.getSlotAssignments('')
                .filter((x) => x instanceof ToggleButtonElement);
            elements.forEach((x) => x.dir = next);
        }
    }
    /**
     * @protected
     */
    onValuePropertyChange(_prev, next) {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement);
        elements.forEach((x) => x.isChecked = next === x.value);
    }
    /**
     * @private
     */
    onToggleChecked(event) {
        const target = event.target;
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ToggleButtonElement);
        this._isSwitching = true;
        elements.filter((x) => x !== target).forEach((x) => x.uncheck());
        this._isSwitching = false;
        this.value = target.value;
        this.onToggleChanged(event);
    }
    /**
     * Prevent deselection of the currently selected button inside the group.
     *
     * @private
     */
    onToggleUnchecked(event) {
        if (this._isSwitching) {
            return;
        }
        const target = event.target;
        // If the unchecked target was the current selection, re-check it to enforce single-selection.
        if (this.value === target.value) {
            target.check();
        }
    }
    /**
     * @private
     */
    clearEvents() {
        this._eventSubscriptions.forEach((x) => x.dispose());
        this._eventSubscriptions = [];
    }
};
__decorate([
    Emit({ eventName: 'toggleChanged' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ToggleButtonGroupElement.prototype, "toggleChanged", null);
__decorate([
    Watch('disabled'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], ToggleButtonGroupElement.prototype, "onDisabledPropertyChange", null);
__decorate([
    Watch('appearance'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ToggleButtonGroupElement.prototype, "onAppearancePropertyChange", null);
__decorate([
    Watch('variant'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ToggleButtonGroupElement.prototype, "onVariantPropertyChange", null);
__decorate([
    Watch('dir'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ToggleButtonGroupElement.prototype, "onDirPropertyChange", null);
__decorate([
    Watch('value'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], ToggleButtonGroupElement.prototype, "onValuePropertyChange", null);
ToggleButtonGroupElement = __decorate([
    Component({
        selector: 'mosaik-toggle-button-group',
        template: toggleButtonGroupElementTemplate,
        themes: {
            joy: buttonGroupElementJoyStyle,
            retro: buttonGroupElementRetroStyle,
            cosmopolitan: buttonGroupElementCosmopolitanStyle
        },
        host: {
            role: 'group'
        },
        imports: [ToggleButtonElement]
    }),
    __metadata("design:paramtypes", [])
], ToggleButtonGroupElement);
export { ToggleButtonGroupElement };
//# sourceMappingURL=ToggleButtonGroupElement.js.map