// #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 { CustomFormData } from './CustomFormData';
import { formElementTemplate } from './FormElementTemplate';
import { FormFieldElement } from './FormFieldElement';
import { formElementJoyStyle } from './Themes/FormElement.Joy';
import { formElementMemphisStyle } from './Themes/FormElement.Memphis';
import { formElementCosmopolitanStyle } from './Themes/FormElement.Cosmopolitan';
import { HTMLElementEventEmitter, on } from '@breadstone/mosaik-elements';
import { Slottable } from '../../Behaviors/Slottable';
// #endregion
/**
 * Form - A structured container for collecting and validating user input data.
 *
 * Provides form submission handling, validation coordination, and data collection across
 * multiple form controls. Supports custom form data serialization and validation workflows.
 * Essential for user registration, settings panels, and data entry interfaces.
 *
 * @name FormElement
 * @element mosaik-form
 * @category Forms
 *
 * @slot - Default content area for form controls and layout elements
 *
 * @csspart form - The main form container element
 *
 * @cssprop --form-background-color - Background color of the form container
 * @cssprop --form-padding - Internal padding for form content
 * @cssprop --form-gap - Spacing between form elements
 * @cssprop --form-border-radius - Border radius for form container
 * @cssprop --form-border-color - Border color around the form
 * @cssprop --form-max-width - Maximum width constraint for the form
 *
 * @dependency FormFieldElement - Provides structured form field layout and validation
 *
 * @example
 * ```html
 * <!-- User registration form -->
 * <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-form-field label="Password" required>
 *     <mosaik-text-field name="password" type="password" required></mosaik-text-field>
 *   </mosaik-form-field>
 *
 *   <div class="form-actions">
 *     <mosaik-button type="reset">Reset</mosaik-button>
 *     <mosaik-button type="submit" appearance="primary">Register</mosaik-button>
 *   </div>
 * </mosaik-form>
 *
 * <!-- Settings form with validation -->
 * <mosaik-form novalidate>
 *   <mosaik-form-field label="Theme Preference">
 *     <mosaik-select name="theme">
 *       <option value="light">Light</option>
 *       <option value="dark">Dark</option>
 *       <option value="auto">System</option>
 *     </mosaik-select>
 *   </mosaik-form-field>
 *
 *   <mosaik-form-field label="Notifications">
 *     <mosaik-checkbox name="emailNotifications">Email notifications</mosaik-checkbox>
 *     <mosaik-checkbox name="pushNotifications">Push notifications</mosaik-checkbox>
 *   </mosaik-form-field>
 *
 *   <mosaik-button type="submit">Save Settings</mosaik-button>
 * </mosaik-form>
 *
 * <!-- Multi-step form -->
 * <mosaik-form method="post" action="/api/submit">
 *   <div class="form-step" data-step="1">
 *     <h3>Personal Information</h3>
 *     <mosaik-form-field label="First Name">
 *       <mosaik-text-field name="firstName"></mosaik-text-field>
 *     </mosaik-form-field>
 *     <mosaik-form-field label="Last Name">
 *       <mosaik-text-field name="lastName"></mosaik-text-field>
 *     </mosaik-form-field>
 *   </div>
 *
 *   <div class="form-actions">
 *     <mosaik-button type="button">Next Step</mosaik-button>
 *   </div>
 * </mosaik-form>
 * ```
 *
 * @fires submitted - Emitted when the form is submitted with form data
 * @fires reseted - Emitted when the form is reset to initial values
 *
 * @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 ('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: 'reseted' }),
    __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