import {locale} from "../stores/LocaleStore";
import {get} from "svelte/store";

import en from "../i18n/en.json";
import jp from "../i18n/jp.json";
import nl from "../i18n/nl.json";
import {Logger, logSetup} from "./logger";

logSetup();
const logger = new Logger("i18n");

export const locales: any = {
    "en": en,
    "jp": jp,
    "nl": nl
}

export function getCurrentLocale(): string {
    return get(locale);
}

export function setLocale(newLocale: string) {
    logger.info(`Setting locale to ${newLocale}`);
    if (!(newLocale in locales)) {
        logger.error(`Locale ${newLocale} does not exist`);
        return false;
    }
    locale.set(newLocale);
    return true;
}

export function t(query: string, locale = ""): string {
    let val: any = locales[locale === "" ? getCurrentLocale() : locale];
    const spl: Array<string> = query.split('.');
    for (let i = 0; i < spl.length; i++) {
        const item = spl[i];
        if (item in val) {
            val = val[item];
        } else {
            logger.info(`missing locale string ${query}`);
            val = "missing: " + query;
            break;
        }
    }
    if (typeof val === "object") {
        logger.info(`query string ${query} is not a message`);
        return "missing: " + query;
    }
    return val;
}