"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeTranslator = exports.Translator = exports.formatPattern = exports.formatString = exports.getPattern = exports.defaultLocale = exports.updateLocale = exports.activeTranslators = exports.activeLocale = void 0;
const bundle_1 = require("@fluent/bundle");
const langneg_1 = require("@fluent/langneg");
const fs = require("fs");
const osl = require("os-locale");
const path = require("path");
const fsutils_1 = require("./fsutils");
const utils_1 = require("./utils");
const ftlFiles = new Map();
const loadFTLDir = (dir) => {
    const files = fs.readdirSync(dir);
    for (const f of files) {
        if (!f.endsWith('.ftl')) {
            continue;
        }
        const locale = path.basename(f, '.ftl').split(' ')[0];
        console.log('found FTL file for', locale);
        if (!ftlFiles.has(locale)) {
            ftlFiles.set(locale, []);
        }
        ftlFiles.get(locale).push(`${dir}/${f}`);
    }
};
loadFTLDir(`${utils_1.appDir}app/assets/ftl`);
const bundleMap = new Map();
exports.activeLocale = '';
exports.activeTranslators = new Set();
let activeBundle = null;
const setLocale = (locale) => {
    if (!ftlFiles.has(locale)) {
        console.warn('WARNING: locale not found, setting to en:', locale);
        locale = 'en';
    }
    if (!bundleMap.has(locale)) {
        const bundle = new bundle_1.FluentBundle(locale, {
            useIsolating: false,
            functions: {
                TRANSLATE: (args) => exports.formatString(args[0]),
            },
        });
        bundleMap.set(locale, bundle);
        for (const f of ftlFiles.get(locale)) {
            const resourceText = fs.readFileSync(f, 'utf8');
            const resource = new bundle_1.FluentResource(resourceText);
            const errors = bundle.addResource(resource);
            if (errors.length > 0) {
                console.warn(`Error loading ${locale} resource:`, errors);
            }
        }
    }
    exports.activeLocale = locale;
    activeBundle = bundleMap.get(exports.activeLocale);
    for (const t of exports.activeTranslators) {
        if (t.id !== '') {
            t.init();
            t.update();
        }
    }
};
let currentLocales = [];
const updateLocale = () => {
    const requestedLanguages = [osl.sync()];
    if (utils_1.objHas(fsutils_1.config, 'locale') && fsutils_1.config.locale !== '') {
        requestedLanguages.unshift(fsutils_1.config.locale);
    }
    currentLocales = langneg_1.negotiateLanguages(requestedLanguages, [...ftlFiles.keys()], { defaultLocale: 'en' });
    console.log('Locales:', currentLocales.join(', '));
    setLocale(currentLocales.length > 0 ? currentLocales[0] : 'en-US');
};
exports.updateLocale = updateLocale;
exports.updateLocale();
exports.defaultLocale = currentLocales.length > 0 ? currentLocales[0] : 'en-US';
const findSpaces = / /g;
const getPattern = (s) => {
    s = s.replace(findSpaces, '-');
    if (!activeBundle.hasMessage(s)) {
        console.warn('WARNING: Pattern not found for', s);
        return null;
    }
    return activeBundle.getMessage(s).value;
};
exports.getPattern = getPattern;
const patternErrors = [];
const formatString = (s, args = null) => {
    s = s.replace(findSpaces, '-');
    if (!activeBundle.hasMessage(s)) {
        return s;
    }
    const ret = activeBundle.formatPattern(activeBundle.getMessage(s).value, args, patternErrors);
    if (patternErrors.length > 0) {
        console.warn('Error formatting string:', s, patternErrors);
        patternErrors.length = 0;
        return '';
    }
    return ret;
};
exports.formatString = formatString;
const formatPattern = (msg, args = null) => {
    const ret = activeBundle.formatPattern(msg, args, patternErrors);
    if (patternErrors.length > 0) {
        console.warn('Error formatting pattern:', activeBundle, msg, patternErrors);
        patternErrors.length = 0;
        return '';
    }
    return ret;
};
exports.formatPattern = formatPattern;
class Translator {
    constructor(id, data = null) {
        this.value = '';
        this.pattern = null;
        this.data = null;
        this.id = id;
        this.data = data;
        exports.activeTranslators.add(this);
    }
    init() {
        this.pattern = exports.getPattern(this.id);
    }
    free() {
        exports.activeTranslators.delete(this);
    }
    refresh(data = null) {
        this.data = data;
        if (this.pattern !== null) {
            this.value = exports.formatPattern(this.pattern, data);
        }
        else {
            this.value = this.id;
        }
    }
    update() {
        this.value = exports.formatPattern(this.pattern, this.data);
    }
    set(id, data = null) {
        this.id = id;
        this.data = data;
        this.init();
        this.update();
    }
}
exports.Translator = Translator;
const makeTranslator = (id, data = null) => {
    const tr = new Translator(id);
    tr.init();
    tr.refresh(data);
    return tr;
};
exports.makeTranslator = makeTranslator;
console.log(exports.makeTranslator('hello-world', { value: ':)' }).value);
//# sourceMappingURL=i18n.js.map