// #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 { Themeable } from '../../../Controls/Behaviors/Themeable';
import { Emit } from '../../../Events/Decorators/EmitDecorator';
import { Attribute } from '../../Decorators/AttributeDecorator';
import { Component } from '../../Decorators/ComponentDecorator';
import { ButtonType } from '../../Types/ButtonType';
import { CustomElement } from '../Abstracts/CustomElement';
import { isButtonBase } from '../Buttons/Abstracts/ButtonBaseElement';
import { CustomFormData } from './CustomFormData';
import { formElementTemplate } from './FormElementTemplate';
import { FormFieldElement } from './FormFieldElement';
import { formElementJoyStyle } from './Themes/FormElement.Joy';
import { formElementRetroStyle } from './Themes/FormElement.Retro';
import { formElementCosmopolitanStyle } from './Themes/FormElement.Cosmopolitan';
import { HTMLElementEventEmitter, on } from '@breadstone/mosaik-elements';
import { Slottable } from '../../Behaviors/Slottable';
// #endregion
/**
 * Form - A component that represents a form container.
 *
 * @description
 * This element serves as a container for form inputs and buttons. *
 *
 * @name Form
 * @element mosaik-form
 * @category Forms
 *
 * @fires submitted {CustomEvent<IFormSubmitEventDetail>} - Fired when the form is submitted.
 * @fires reseted {CustomEvent<IFormResetEventDetail>} - Fired when the form is reseted.
 *
 * @slot - The default slot where form controls can be placed.
 *
 * @csspart form - The part representing the form container itself.
 *
 * @example
 * ```html
 * <mosaik-form>
 *   <input type="text" name="username" placeholder="Username">
 *   <input type="password" name="password" placeholder="Password">
 *   <button type="submit">Submit</button>
 * </mosaik-form>
 * ```
 *
 * @public
 */
let FormElement = class FormElement extends Themeable(Slottable(CustomElement)) {
    // #region Fields
    _submitted;
    _reseted;
    _submitSubscription;
    _resetSubscription;
    _formElement;
    _novalidate;
    _autocomplete;
    _name;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._novalidate = false;
        this._autocomplete = false;
        this._submitted = new HTMLElementEventEmitter(this, 'submitted');
        this._reseted = new HTMLElementEventEmitter(this, 'reseted');
        this._submitSubscription = null;
        this._resetSubscription = null;
        this._name = '';
    }
    // #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-form';
    }
    /**
     * Gets or sets the `novalidate` property.
     *
     * @public
     * @attr
     */
    get novalidate() {
        return this._novalidate;
    }
    set novalidate(value) {
        if (this._novalidate !== value) {
            this._novalidate = value;
            this.requestUpdate('novalidate');
        }
    }
    /**
     * 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 `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Called when the form is submitted.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get submitted() {
        return this._submitted;
    }
    /**
     * Called when the form is reseted.
     * Provides reference to `{@link IEventDetail}` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get reseted() {
        return this._reseted;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        super.disconnectedCallback();
        this._submitSubscription?.dispose();
        this._resetSubscription?.dispose();
    }
    /**
     * Submits the form. It returns `true` if the form is valid, otherwise it returns `false`.
     *
     * @public
     */
    submit() {
        if (!this._novalidate && !this.reportValidity()) {
            return false;
        }
        // This._formElement?.submit();
        this.onSubmitted({ data: this.getFormData() });
        return true;
    }
    /**
     * Resets the form.
     *
     * @public
     */
    reset() {
        // This._formElement?.reset();
        this.getFormFields()
            .filter((x) => x instanceof FormFieldElement)
            .forEach((element) => element.formResetCallback?.());
        this.onReseted({});
    }
    /**
     * Reports the validity of the form.
     * It returns `true` if the form is valid, otherwise it returns `false`.
     *
     * @public
     */
    reportValidity() {
        const formElements = this.getFormFields()
            .filter((x) => x instanceof FormFieldElement);
        const isValid = formElements.every((element) => typeof element.reportValidity === 'function' ? element.reportValidity() : true);
        return isValid;
    }
    /**
     * Checks the validity of the form.
     * It returns `true` if the form is valid, otherwise it returns `false`.
     *
     * @public
     */
    checkValidity() {
        const formElements = this.getFormFields()
            .filter((x) => x instanceof FormFieldElement);
        const isValid = formElements.every((element) => typeof element.checkValidity === 'function' ? element.checkValidity() : true);
        return isValid;
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this.on('click', (event) => {
            this.onClick(event);
        });
        this._formElement = this.getTemplatePart('form');
        this._submitSubscription = on(this._formElement, 'submit', (e) => {
            e.preventDefault();
            this.onSubmitted({ data: this.getFormData() });
        });
        this._resetSubscription = on(this._formElement, 'reset', (e) => {
            e.preventDefault();
            this.getFormFields()
                .filter((x) => x instanceof FormFieldElement)
                .forEach((element) => element.formResetCallback?.());
            this.onReseted({});
        });
    }
    /**
     * Emits the {@link reseted} event.
     *
     * @protected
     */
    onReseted(args) {
        this._reseted.emit(args);
    }
    /**
     * Emits the {@link submitted} event.
     *
     * @protected
     */
    onSubmitted(args) {
        this._submitted.emit(args);
    }
    /**
     * @private
     */
    getFormData() {
        const formName = this.hasAttribute('name')
            ? this.getAttribute('name')
            : null;
        const formData = new CustomFormData(this._formElement, undefined, formName ?? undefined);
        this.getFormFields()
            .filter((x) => x instanceof FormFieldElement)
            .filter((x) => !x.disabled)
            .forEach((element) => {
            const name = element.name || element.hasAttribute('name')
                ? element.getAttribute('name')
                : null;
            if (name) {
                const value = element.getFormValue() ?? '';
                if (value instanceof CustomFormData) {
                    value.forEach((v, k) => {
                        formData.append(k, v);
                    });
                }
                if (value instanceof File) {
                    formData.append(name, value, value.name);
                }
                if (typeof value === 'string') {
                    formData.append(name, value);
                }
            }
            else {
                throw new Error('The form field must have a name.');
            }
        });
        return formData;
    }
    /**
     * @private
     */
    getFormFields() {
        return this.getSlotAssignments('');
    }
    /**
     * @private
     */
    onClick(event) {
        const element = event.target;
        if (isButtonBase(element)) {
            if (element.type === ButtonType.Submit) {
                event.preventDefault();
                this.submit();
            }
            else if (element.type === ButtonType.Reset) {
                event.preventDefault();
                this.reset();
            }
        }
    }
};
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FormElement.prototype, "novalidate", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], FormElement.prototype, "autocomplete", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], FormElement.prototype, "name", null);
__decorate([
    Emit({ eventName: 'submitted' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FormElement.prototype, "submitted", null);
__decorate([
    Emit({ eventName: 'reseted' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FormElement.prototype, "reseted", null);
FormElement = __decorate([
    Component({
        selector: 'mosaik-form',
        template: formElementTemplate,
        themes: {
            joy: formElementJoyStyle,
            retro: formElementRetroStyle,
            cosmopolitan: formElementCosmopolitanStyle
        },
        imports: []
    }),
    __metadata("design:paramtypes", [])
], FormElement);
export { FormElement };
//# sourceMappingURL=FormElement.js.map