let {
    FG_COLOR,
    BG_COLOR,
    BASE_COLORS,
    DELIMITERS,
    KEY_WORDS,
    KEY_WORDS_COLORS
} = require('../src/constants/LoggerConsts');

let MESSAGES = {};

function init(msg, delimiter) {
    MESSAGES = msg;

    if (delimiter) {
        const { color, text } = delimiter;
        DELIMITERS.TEXT = text;
        DELIMITERS.COLOR = color;
    }
}
/**
 * Logs message from setted mapping after key words was colored and placeholders replaced.
 * @param {String} msgType key of message from Messages mapping.
 * @param {Object} opts placeholder: text, default marker for replace: $placeholder$.
 */
function log(msgType, opts) {
    let msg = MESSAGES[msgType];

    if (!msg || !msg.length) return;

    msg = _replacePlaceholders(msg, opts);

    msg = _paintKeyWords(msg);

    console.log(msg);
}

function _paintKeyWords(rawMsg) {
    return Object.keys(KEY_WORDS).reduce((acc, keyWordTypeKey) => {
        const modifiedKeyWords = KEY_WORDS[keyWordTypeKey].map((keyWord) => {
            return `\\s${keyWord}`;
        });

        const searchReg = new RegExp(modifiedKeyWords.join('|'), "g");

        acc = acc.replace(searchReg, function () {
            const strMatch = arguments[0];
            return `${FG_COLOR[KEY_WORDS_COLORS[keyWordTypeKey]]}${strMatch}${BASE_COLORS.RESET}`;
        });

        return acc;
    }, rawMsg);
}

function _replacePlaceholders(rawMsg, opts) {
    if (!opts) { return rawMsg };

    let msg = rawMsg;

    Object.keys(opts).forEach((key) => {
        const placeholder = `\\$${key}\\$`;

        msg = msg.replace(new RegExp(placeholder, "g"), opts[key]);
    });

    return msg;
}

module.exports = {
    init,
    log
};
