import { getSetting, registerSettings } from "./settings.js";

export const MODULE_ID = "dnd5e-system-customizer";

export let ORIGINAL_CONFIG = {};

export let ORIGINAL_SYSTEM_CONFIG = {};

Hooks.on("init", () => {
    onPostInit();
});

function onPostInit() {
    registerSettings();
    const configKey = getSetting("configKey");
    const systemConfig = foundry.utils.getProperty(window, configKey);
    if (systemConfig) {
        ORIGINAL_SYSTEM_CONFIG = foundry.utils.deepClone(systemConfig);
        delete ORIGINAL_SYSTEM_CONFIG.trackableAttributes;
    } else {        
        Hooks.once("ready", () => {
            ui.notifications.warn("dnd5e-system-customizer.noConfig", { permanent: true, localize: true });
        });
        return;
    }

    const ORIGINAL_TRACKABLE_ATTRIBUTES = [...(systemConfig.trackableAttributes ?? [])];

    const merged = foundry.utils.mergeObject(systemConfig, foundry.utils.deepClone(getSetting("customizationJson") ?? {}));
    if (merged.trackableAttributes) merged.trackableAttributes = ORIGINAL_TRACKABLE_ATTRIBUTES;
    deleteKeys(merged);
}

function deleteKeys(obj) {

    if(!obj) return;
    //crawl the object recursively and delete the object if it has the "unsafelyDelete": true property
    const isObject = typeof obj === 'object' && !Array.isArray(obj) && obj !== null
    const isArray = Array.isArray(obj)
    if (!isObject && !isArray) return;
    
    if (isObject) {
        for (const key of Object.keys(obj)) {
            const val = obj[key];
            if(val?.unsafelyDelete) delete obj[key];
            else deleteKeys(val);
        }
    }else if(isArray){
        for(const val of obj){
            deleteKeys(val);
        }
    }
}