import * as EN from "../resources/lang/en.json";
import * as ES from "../resources/lang/es.json";
import { getLang } from "../utils/helpers";
const strings = {
    en: EN,
    es: ES,
};
export class LangService {
    /**
     * Init service
     *
     * @param _ Locale strings collection
     */
    constructor(_ = {}) {
        this._ = _;
        const locale = getLang();
        this.set(locale);
        this._ = strings[LangService.locale].default;
        const observer = new MutationObserver(function (mutations) {
            mutations.forEach((mutation) => {
                if (mutation.type === "attributes" && locale != LangService.locale) {
                    LangService.locale = locale;
                    if (strings && Object.keys(strings).includes(locale)) {
                        this._ = strings[LangService.locale].default;
                    }
                }
            });
        });
        observer.observe(document.querySelector('html'), { attributes: true });
    }
    /**
     * Set global locale
     *
     * @param locale
     */
    set(locale) {
        if (['en', 'es'].includes(locale)) {
            LangService.locale = locale;
            document.querySelector('html').setAttribute('lang', locale);
        }
        this._ = strings[LangService.locale].default;
    }
    /**
     * Get translate string by key identifier
     *
     * @param key
     * @param replace
     * @returns
     */
    get(key, replace = {}) {
        try {
            let text = this._[key];
            if (!text)
                return key;
            for (const find of Object.keys(replace)) {
                const value = replace[find];
                const regex = new RegExp(`:${find}(\\(([^)]*)\\))?`, 'g');
                text = text.replace(regex, (_parens, parens, inside) => {
                    if (!parens) {
                        return value;
                    }
                    if (inside.includes('|')) {
                        const [singular, plural] = inside.split('|');
                        return value == 1 ? singular : plural;
                    }
                    else {
                        return value == 1 ? '' : inside;
                    }
                });
            }
            return text;
        }
        catch (error) {
            console.warn('LangService.get error:', error);
            return key;
        }
    }
    /**
     * Create service
     *
     * @returns
     */
    static create() {
        const instance = new LangService();
        return Object.assign((key, replace) => instance.get(key, replace), {
            set: (locale) => instance.set(locale),
            get: (key, replace) => instance.get(key, replace),
            locale: LangService.locale,
        });
    }
}
/**
 * Global locale
 */
LangService.locale = 'es';
export const Lang = LangService.create();
