const { DialogV2 } = foundry.applications.api;
const { renderTemplate } = foundry.applications.handlebars;
const { FormDataExtended } = foundry.applications.ux;

async function _dialogWithForm(title, templatePath, templateData) {
    const htmlContent = await renderTemplate(templatePath, templateData);
    const theme = game.settings.get("mgt2", "theme");
    return await DialogV2.wait({
        window: { title },
        content: htmlContent,
        rejectClose: false,
        buttons: [
            {
                action: "submit",
                label: game.i18n.localize("MGT2.Save"),
                icon: '<i class="fa-solid fa-floppy-disk"></i>',
                default: true,
                callback: (event, button, dialog) => {
                    return new FormDataExtended(dialog.element.querySelector('form')).object;
                }
            }
        ]
    });
}

export class CharacterPrompts {

    static async openConfig(system) {
        return _dialogWithForm(
            "Configuration",
            "systems/mgt2/templates/actors/actor-config-sheet.html",
            { config: CONFIG.MGT2, system }
        );
    }

    static async openCharacteristic(name, show, showMax, showAll = false) {
        return _dialogWithForm(
            "Configuration: " + name,
            "systems/mgt2/templates/actors/actor-config-characteristic-sheet.html",
            { name, show, showMax, showAll }
        );
    }

    static async openTraitEdit(data) {
        const title = data.name ?? game.i18n.localize("MGT2.Actor.EditTrait");
        return _dialogWithForm(
            title,
            "systems/mgt2/templates/actors/trait-sheet.html",
            { config: CONFIG.MGT2, data }
        );
    }

    static async openEditorFullView(title, html) {
        const htmlContent = await renderTemplate("systems/mgt2/templates/editor-fullview.html", {
            config: CONFIG.MGT2,
            html
        });
        const theme = game.settings.get("mgt2", "theme");
        await DialogV2.wait({
            window: { title },
            content: htmlContent,
            rejectClose: false,
            buttons: [
                {
                    action: "close",
                    label: game.i18n.localize("MGT2.Close") || "Fermer",
                    default: true,
                    callback: () => null
                }
            ]
        });
    }
}