// text_handling
// A module to handle fetching text for Legends of Learning games; if LoL isn't present,
// it assumes text is stored normally.

let lolLanguage;
let usingLoL = false;
async function initializeTextHandling({config, useLoL}) {
    // In order for LoL to be used, both arguments config and useLoL must be defined
    // and useLOL must explicitly be set true.
    // Also, the lol_language module must be found.

    if (!config && !useLoL) {
        usingLoL = false;
        return false;
    }

    try {
        lolLanguage = await import("./lol_language.js");
    }
    catch (e) {
        console.log("Caught it!");
        lolLanguage = undefined;
    }

    if (lolLanguage) {
        lolLanguage.setPrefix(config.options.lolPrefix);
        usingLoL = true;
        return true;
    }
    else {
        usingLoL = false;
        return false;
    }

}

function getText(textArg) {
    // If textArg is a string, the function just returns the string.
    //
    // In order for LoL to be used to retrieve the string:
    // 1. textArg must be an object. It will usually have the form
    //    {text: "some text", keyPathLoL: "the key to use with LOL language dictionary"}
    // 2. usingLoL must be true (which means it had to be explicitly set true
    //    in initializeTextHandling)
    // 3. keyPathLoL must return a valid string when used with getTextForKeyPath
    //
    // If conditions 2 and three are not both true, then textArg.text is returned.
    // If textArg.text is not defined, null is returned.

    switch (typeof textArg) {
        case "string":
            return textArg;
        case "object":
            if (usingLoL && textArg?.keyPathLoL) {
                return lolLanguage.getTextForKeyPath(textArg.keyPathLoL);
            }
            else {
                return textArg?.text ?? null;
            }
        default:
            return null;
    }
}

export {usingLoL, initializeTextHandling, getText}