// #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 { HTMLElementEventEmitter, on } from '@breadstone/mosaik-elements';
import { Themeable } from '../../../Controls/Behaviors/Themeable';
import { Emit } from '../../../events/Decorators/EmitDecorator';
import { Slottable } from '../../Behaviors/Slottable';
import { Attribute } from '../../Decorators/AttributeDecorator';
import { Component } from '../../Decorators/ComponentDecorator';
import { ButtonType } from '../../Types/ButtonType';
import { CustomElement } from '../Abstracts/CustomElement';
import { CustomFormData } from './CustomFormData';
import { formElementTemplate } from './FormElementTemplate';
import { FormFieldElement } from './FormFieldElement';
import { formElementCosmopolitanStyle } from './Themes/FormElement.Cosmopolitan';
import { formElementJoyStyle } from './Themes/FormElement.Joy';
import { formElementMemphisStyle } from './Themes/FormElement.Memphis';
// #endregion
/**
 * Form - A structured container for collecting and validating user input data.
 *
 * @description
 * The Form component is a fundamental container for user data entry that provides comprehensive
 * form submission handling, validation coordination, and data collection across multiple form
 * controls. It supports custom form data serialization, automatic validation workflows, and
 * standard HTML form behaviors including submit and reset actions. The component acts as a
 * central coordinator for form fields, managing validation state, collecting form data, and
 * emitting events for form lifecycle actions. Essential for user registration, settings panels,
 * data entry interfaces, and any scenario requiring structured user input collection with
 * validation support.
 *
 * @name Form
 * @element mosaik-form
 * @category Forms
 *
 * @slot - Default content area for form controls, form fields, and layout elements
 *
 * @csspart form - The main form container element
 *
 * @cssprop {String} --form-background-color - The background color of the form container
 *
 * @dependency {FormFieldElement} - Structured form field layout with label and validation support
 *
 * @fires submitted {FormSubmitEvent} - Fired when the form is submitted with collected form data
 * @fires formReset {FormResetEvent} - Fired when the form is reset to initial values
 *
 * @example
 * Basic user registration form:
 * ```html
 * <mosaik-form id="registrationForm">
 *   <mosaik-form-field label="Full Name" required>
 *     <mosaik-text-field name="fullName" required></mosaik-text-field>
 *   </mosaik-form-field>
 *   <mosaik-form-field label="Email" required>
 *     <mosaik-text-field name="email" type="email" required></mosaik-text-field>
 *   </mosaik-form-field>
 *   <mosaik-button type="submit" variant="primary">Register</mosaik-button>
 * </mosaik-form>
 * ```
 *
 * @example
 * Form with validation disabled:
 * ```html
 * <mosaik-form novalidate autocomplete>
 *   <mosaik-form-field label="Username">
 *     <mosaik-text-field name="username"></mosaik-text-field>
 *   </mosaik-form-field>
 *   <mosaik-button type="submit">Submit</mosaik-button>
 *   <mosaik-button type="reset">Reset</mosaik-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, 'formReset');
        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();
        const formData = this.getFormData();
        const values = {};
        formData.forEach((v, k) => { values[k] = v; });
        this.onSubmitted({ formData: formData, values: values });
        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();
            const formData = this.getFormData();
            const values = {};
            formData.forEach((v, k) => { values[k] = v; });
            this.onSubmitted({ formData: formData, values: values });
        });
        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 ('type' in element && ('disabled' in element) && !element.disabled) {
            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: 'formReset' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], FormElement.prototype, "reseted", null);
FormElement = __decorate([
    Component({
        selector: 'mosaik-form',
        template: formElementTemplate,
        themes: {
            joy: formElementJoyStyle,
            memphis: formElementMemphisStyle,
            cosmopolitan: formElementCosmopolitanStyle
        },
        imports: []
    }),
    __metadata("design:paramtypes", [])
], FormElement);
export { FormElement };
//# sourceMappingURL=FormElement.js.map