// #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 { DomServiceLocator } from '../../../../Dom/Dom';
import { waitForEvent } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Key } from '../../../Types/Key';
import { PinMode } from '../../../Types/PinMode';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { pinBoxElementTemplate } from './PinBoxElementTemplate';
import { pinBoxElementJoyStyle } from './Themes/PinBoxElement.Joy';
import { pinBoxElementRetroStyle } from './Themes/PinBoxElement.Retro';
import { pinBoxElementCosmopolitanStyle } from './Themes/PinBoxElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
// #endregion
/**
 * Pin Box - A user interface component for securely inputting personal identification numbers (PINs).
 *
 * @element mosaik-pinbox
 *
 * @description
 * The Pin Box component is designed for entering personal identification numbers (PINs) and other numeric codes.
 * It provides a secure input method and is commonly used in scenarios where users need to enter confidential numeric data,
 * such as PIN-based authentication.
 *
 * @category Forms
 *
 * @keyhandle Backspace - Deletes the character to the left of the cursor.
 * @keyhandle LeftArrow - Moves the cursor to the left.
 * @keyhandle RightArrow - Moves the cursor to the right.
 *
 * @public
 */
let PinBoxElement = class PinBoxElement extends Themeable(Disableable(Invalidable(Valueable(Variantable(Appearanceable(InputBaseElement)))))) {
    // #region Fields
    _keyboardController;
    _value;
    _readonly;
    _required;
    _autofocus;
    _name;
    _pattern;
    _placeholder;
    _autocomplete;
    _length;
    _focusedIndex;
    _mode;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._value = '';
        this._readonly = false;
        this._required = false;
        this._autofocus = false;
        this._name = '';
        this._pattern = '';
        this._placeholder = '';
        this._autocomplete = false;
        this._length = 4;
        this._focusedIndex = -1;
        this._mode = PinMode.Text;
        this._keyboardController = new KeyboardController(this);
    }
    // #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-pinbox';
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `readonly` property.
     *
     * @public
     * @attr
     */
    get readonly() {
        return this._readonly;
    }
    set readonly(value) {
        if (this._readonly !== value) {
            this._readonly = value;
            this.requestUpdate('readonly');
        }
    }
    /**
     * Gets or sets the `required` property.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Gets or sets the `autofocus` property.
     *
     * @public
     * @override
     */
    get autofocus() {
        return this._autofocus;
    }
    set autofocus(value) {
        if (this._autofocus !== value) {
            this._autofocus = value;
            this.requestUpdate('autofocus');
        }
    }
    /**
     * Gets or sets the `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Gets or sets the `pattern` property.
     *
     * @public
     * @attr
     */
    get pattern() {
        return this._pattern;
    }
    set pattern(value) {
        if (this._pattern !== value) {
            this._pattern = value;
            this.requestUpdate('pattern');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     * @attr
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `autocomplete` property.
     *
     * @public
     * @attr
     */
    get autocomplete() {
        return this._autocomplete;
    }
    set autocomplete(value) {
        if (this._autocomplete !== value) {
            this._autocomplete = value;
            this.requestUpdate('autocomplete');
        }
    }
    /**
     * Gets or sets the `length` property.
     *
     * @public
     * @attr
     */
    get length() {
        return this._length;
    }
    set length(value) {
        if (this._length !== value) {
            this._length = value;
            this.requestUpdate('length');
        }
    }
    /**
     * Gets or sets the `mode` property.
     *
     * @public
     * @attr
     */
    get mode() {
        return this._mode;
    }
    set mode(value) {
        if (this._mode !== value) {
            this._mode = value;
            this.requestUpdate('mode');
        }
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this.on('paste', (e) => {
            this.setValue(e.clipboardData?.getData('text/plain') ?? '');
        });
        this._keyboardController
            .add([
            Key.Backspace,
            Key.LeftArrow
        ], () => {
            const current = this.getInputs()[this._focusedIndex];
            if (!current.value.length || current.selectionStart === 0) {
                this.getInputs()[this._focusedIndex - 1]?.focus();
            }
        })
            .add([Key.RightArrow], () => {
            const current = this.getInputs()[this._focusedIndex];
            if (!current.value.length || current.selectionStart === 1) {
                this.getInputs()[this._focusedIndex + 1]?.focus();
            }
        });
    }
    /**
     * @public
     * @override
     */
    focus() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.focus();
        }
    }
    /**
     * @public
     * @override
     */
    blur() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.blur();
        }
    }
    /**
     * @public
     */
    clear() {
        this.value = '';
        this.removeAttribute('value');
        this.emit('change', {
            bubbles: true,
            composed: true
        });
        // afterwards focus the input
        this.focus();
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     * @override
     */
    reset() {
        super.reset();
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this.getTemplatePart('input').checkValidity()
            : true;
    }
    /**
     * @protected
     * @template
     */
    onChange(event) {
        this.setValue(event.target.value);
        this.emit('change', { detail: this.value });
    }
    /**
     * @protected
     * @override
     * @template
     */
    onInput(event) {
        super.onInput(event);
        this.setValue(event.target.value);
        this.emit('input', { detail: this.value });
    }
    /**
     * @protected
     * @override
     * @template
     */
    onFocus(event) {
        super.onFocus(event);
        this._focusedIndex = this.getInputs().indexOf(event.target);
        this.emit('focus', { detail: event });
    }
    /**
     * @protected
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        this._focusedIndex = -1;
        this.emit('blur', { detail: event });
    }
    /**
     * @private
     */
    getInputValues() {
        return this.getInputs().map((x) => x.value);
    }
    /**
     * @private
     */
    getInputs() {
        return this.shadowRoot
            ? DomServiceLocator.current.findDescendants(this.shadowRoot, 'input') ?? []
            : [];
    }
    /**
     * @private
     */
    replaceAt(array, index, value) {
        const newArray = [...array];
        newArray[index] = value;
        return newArray;
    }
    /**
     * @private
     */
    setValue(value) {
        const startIndex = this._focusedIndex;
        const rangeValue = value.substring(0, this._length);
        const rangeValueLength = rangeValue.length;
        if (rangeValueLength > 1) {
            for (let i = startIndex; i < rangeValue.length; i++) {
                const char = rangeValue[i];
                const input = this.getInputs()[i];
                // set value of input
                input.value = char;
                // afterwards, focus next input
                void waitForEvent(input, 'blur').then(() => {
                    this.getInputs()[i + 1]?.focus();
                });
                input.blur();
            }
        }
        else {
            const char = rangeValue;
            const input = this.getInputs()[startIndex];
            // set value of input
            input.value = char;
            // afterwards, focus next input
            void waitForEvent(input, 'blur').then(() => {
                this.getInputs()[startIndex + 1]?.focus();
            });
            input.blur();
        }
        this.value = this.getInputValues().join('');
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "pattern", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], PinBoxElement.prototype, "length", null);
__decorate([
    Attribute({ type: PinMode }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "mode", null);
PinBoxElement = __decorate([
    Component({
        selector: 'mosaik-pinbox',
        template: pinBoxElementTemplate,
        themes: {
            joy: pinBoxElementJoyStyle,
            retro: pinBoxElementRetroStyle,
            cosmopolitan: pinBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        imports: [FocusRingElement]
    }),
    __metadata("design:paramtypes", [])
], PinBoxElement);
export { PinBoxElement };
//# sourceMappingURL=PinBoxElement.js.map