import { MODULE_ID } from "../main.js";

export class LockConfiguration extends FormApplication {
    constructor(document, formConfiguration, LockCLS) {
        super();
        this.document = document;
        this.formConfiguration = formConfiguration;
        this.LockCLS = LockCLS;
    }

    static get APP_ID() {
        return this.name
            .split(/(?=[A-Z])/)
            .join("-")
            .toLowerCase();
    }

    get APP_ID() {
        return this.constructor.APP_ID;
    }

    static get defaultOptions() {
        return foundry.utils.mergeObject(super.defaultOptions, {
            id: this.APP_ID,
            template: `modules/${MODULE_ID}/templates/${this.APP_ID}.hbs`,
            popOut: true,
            minimizable: true,
            closeOnSubmit: true,
            width: 500,
        });
    }

    async getData() {
        const data = this.document.getFlag(MODULE_ID, this.formConfiguration.type) ?? {};
        const formConfig = foundry.utils.deepClone(this.formConfiguration);
        formConfig.inputs.forEach((input) => {
            input.value = data[input.name] ?? input.value;
            input.label ??= game.i18n.localize(`${MODULE_ID}.${this.formConfiguration.type}.${input.name}.label`);
        });
        formConfig.puzzleDescription = game.i18n.localize(`${MODULE_ID}.${this.formConfiguration.type}.description`);
        formConfig.playerInfo = game.i18n.localize(`${MODULE_ID}.${this.formConfiguration.type}.playerInfo`);
        return { ...formConfig };
    }

    get title() {
        return game.i18n.localize(`${MODULE_ID}.${this.formConfiguration.type}.name`);
    }

    activateListeners(html) {
        super.activateListeners(html);
        html = html[0] ?? html;
        if (this.formConfiguration.activateListeners) {
            this.formConfiguration.activateListeners(html, this);
        }
        html.querySelector("#reset").addEventListener("click", async (e) => {
            e.preventDefault();
            const defaultFlag = this.LockCLS.defaultState;
            await this.document.setFlag(MODULE_ID, `${this.formConfiguration.type}`, defaultFlag);
            ui.notifications.info(game.i18n.localize(`${MODULE_ID}.notifications.resetSuccess`));
        });
    }

    async _updateObject(event, formData) {
        formData = foundry.utils.expandObject(formData);
        return this.document.setFlag(MODULE_ID, this.formConfiguration.type, formData);
    }
}
