import { MODULE_ID, DEFAULT_CUSTOMIZATIONS } from "./main.js";
import { JsonEditorApp } from "./app/app.js";

export function registerSettings() {
    //create an all caps version of the system id for use in settings
    const SYSTEM_ID = game.system.id.toUpperCase();
    const defaultConfigKey = CONFIG[SYSTEM_ID] ? `CONFIG.${SYSTEM_ID}` : `CONFIG.${game.system.id}`;

    const settings = {
        customizationJson: {
            scope: "world",
            config: false,
            type: Object,
            default: {},
        },
        configKey: {
            name: `${MODULE_ID}.settings.configKey.name`,
            hint: `${MODULE_ID}.settings.configKey.hint`,
            scope: "world",
            config: true,
            type: String,
            default: defaultConfigKey,
        },
    };

    registerSettingsArray(settings);

    game.settings.registerMenu(MODULE_ID, "JSONEditor", {
        name: game.i18n.localize(`${MODULE_ID}.settings.jsonEditor.name`),
        label: game.i18n.localize(`${MODULE_ID}.settings.jsonEditor.label`),
        hint: game.i18n.localize(`${MODULE_ID}.settings.jsonEditor.hint`),
        icon: "fas fa-cogs",
        scope: "world",
        restricted: true,
        type: JsonEditorApp,
    });

    Hooks.on("renderSettingsConfig", (app, html) => {
        html = html[0] ?? html;
        const btn = html.querySelector('button[data-key="dnd5e-system-customizer.JSONEditor"]');
        const pWarn = document.createElement("p");
        pWarn.classList.add("notification");
        pWarn.classList.add("warning");
        pWarn.innerHTML = game.i18n.localize(`${MODULE_ID}.settings.jsonEditor.warn`);
        btn.closest(".form-group").querySelector(".notes").after(pWarn);
    });
}

export function getSetting(key) {
    return game.settings.get(MODULE_ID, key);
}

export async function setSetting(key, value) {
    return await game.settings.set(MODULE_ID, key, value);
}

function registerSettingsArray(settings) {
    for (const [key, value] of Object.entries(settings)) {
        game.settings.register(MODULE_ID, key, value);
    }
}
