{"size": 1603, "ext": "js", "max_stars_repo_path": "src/i18n/index.js", "max_stars_repo_name": "SlimIO/CLI", "max_stars_repo_stars_event_min_datetime": "2019-12-05T02:51:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-15T13:53:40.000Z", "max_issues_repo_path": "src/i18n/index.js", "max_issues_repo_name": "SlimIO/CLI", "max_issues_repo_issues_event_min_datetime": "2019-12-26T15:32:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T21:40:41.000Z", "max_forks_repo_path": "src/i18n/index.js", "max_forks_repo_name": "SlimIO/CLI", "max_forks_repo_forks_event_min_datetime": "2020-07-15T13:46:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T17:20:22.000Z"}
{"max_stars_count": 2, "max_issues_count": 124, "max_forks_count": 2, "avg_line_length": 21.6621621622, "max_line_length": 70, "alphanum_fraction": 0.6001247661}
/* eslint-disable global-require */
"use strict";

// Require Third-party Depedencies
const cacache = require("cacache");
const is = require("@slimio/is");
const get = require("lodash.get");

// CONSTANTS
const CACHE_PATH = "/tmp/slimio-cli";
const DEFAULT_LANG = "english";

const TOKENS = {
    english: require("./english.js"),
    french: require("./french.js")
};

// VARS
let LANG_UPDATED = true;
let localLang = DEFAULT_LANG;

/**
 * @async
 * @function getLocalLang
 * @returns {string}
 */
function getLocalLang() {
    if (LANG_UPDATED) {
        try {
            const { data } = cacache.get.sync(CACHE_PATH, "cli-lang");
            localLang = data.toString();
        }
        catch (error) {
            cacache.put(CACHE_PATH, "cli-lang", DEFAULT_LANG);
            localLang = DEFAULT_LANG;
        }
        LANG_UPDATED = false;
    }

    return localLang;
}

/**
 * @function getToken
 * @param {string} token lang token
 * @param {any[]} params
 * @returns {string}
 *
 * @throws {TypeError}
 */
function getToken(token, ...params) {
    if (typeof token !== "string") {
        throw new TypeError("token must be a string");
    }

    const lang = getLocalLang();
    if (!Reflect.has(TOKENS, lang)) {
        return `Invalid i18n lang -> ${lang}`;
    }

    const langToken = get(TOKENS[lang], token);
    if (is.nullOrUndefined(langToken)) {
        return `Invalid i18n token -> ${token} for lang -> ${lang}`;
    }

    return params.length === 0 ? langToken : langToken(...params);
}

module.exports = {
    getToken,
    getLocalLang,
    CONSTANTS: { LANG_UPDATED }
};
