import React from 'react';
import PropTypes from 'prop-types';

function getText(key, variables, notranslate) {
    const langsData = getItemFromLocalStorage('strings_langs');
    const env = 'prod';

    if (notranslate || !langsData) {
        return key;
    }

    const string = langsData && langsData.find((item) => item.key === key);
    return string && string.translation ? replaceVariables(string.translation, variables) : getKeyHelper(key, env);
}

/*
 * Find and replace variables in translation.
 * More details here: https://docs.lokalise.co/developer-docs/universal-placeholders
 */
function replaceVariables(translation, variables) {
    if (variables && !Object.keys(variables).length) {
        return translation;
    }

    return translation.replace(/\[\%s\:([\w-_]+?)\]/g, (match, key) => {
        if (key in variables) {
            return variables[key];
        }
        console.warn(`There is no variable for key "${key}" in "${translation}"`);
        return '';
    });
}

function getItemFromLocalStorage(key) {
    return JSON.parse(window.localStorage.getItem(key));
}

function getKeyHelper(key, env) {
    if (key !== '' && env !== 'prod' && parseInt((typeof SHOW_TRANSLATE_ERRORS === 'undefined' ? 1 : SHOW_TRANSLATE_ERRORS), 10)) {
        console.error(`Key "${key}" not found`);
    }

    return key;
}

const Translate = ({tag, variables, notranslate}) => (<span dangerouslySetInnerHTML={{__html: getText(tag, variables, notranslate)}} />);

Translate.propTypes = {
    tag: PropTypes.string.isRequired,
    variables: PropTypes.object,
    notranslate: PropTypes.bool,
};

Translate.defaultProps = {
    variables: {},
    notranslate: false,
};

export default Translate;
