import React from 'react';

/**
 * trim and switch the first character to lowercase
 * @param text
 * @returns {string}
 */
export const lowerFirst = text => {
    if (!text) {
        return '';
    }
    const txt = text.trim();

    return txt.charAt(0).toLowerCase() + txt.slice(1);
};

/**
 * Capitalizes the first character of a string
 * @param {string} word
 * @returns {string} - A string with the first character capitalized
 */
export const upperFirst = (word = '') => (
    word && (word.trim().charAt(0).toUpperCase() + word.slice(1))
);

/**
 * Capitalizes the first character of a string and convert the rest to lowercase
 * @param {string} word
 * @returns {string} - A string with the first character capitalized and the rest lowercase
 */
export const lowercaseWithUpperFirst = (word = '') => (
    word && (word.trim().charAt(0).toUpperCase() + word.slice(1).toLowerCase())
);

/**
 * Removed all spaces in a string
 * @param {string} string
 * @returns {string} - A string with spaces removed
 */
export const normalizeString = string => string && string.replace(/[ ]/g, '');

export const unescapeHtml = html => {
    const wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    return wrapper.textContent;
};

/**
 * strips the slash from the start of a string (usually unit or frequency in the price object comes with a slash)
 * @param text
 * @returns {*|void|string|never}
 */
export const stripSlash = text => text.replace(/^\/[ ]*/, '');

/**
 * Cuts long string at maximum length without cutting in the middle of a word
 * unless requested length is shorter than first word
 * @param {string} text
 * @param {number} maxLength
 * @param {string} ellipsis The ellipsis to add at the end of cut string, default '...'
 * @returns {string}
 */
export const truncateAtWord = (text, maxLength, ellipsis = '...') => {
    if (!text || maxLength <= 0 || text.length <= maxLength) {
        return text;
    }
    // truncate past the length to include punctuation/space, to get last word if it finishes exactly at length
    let truncated = text.substring(0, maxLength + 2);
    while (truncated.length > maxLength) {
        let lastSpace = truncated.lastIndexOf(' ');
        // if no space, truncate string to exact request length
        if (lastSpace === -1) {
            lastSpace = maxLength;
        }
        // remove trailing punctuation characters
        truncated = truncated.substring(0, lastSpace).replace(/[:!?.;,\s]+$/i, '');
    }
    return `${truncated}${ellipsis}`;
};

/**
 * Replaces \n in texts by <br>
 * @param {string} text
 * @returns {Array}
 */
export function newlineToBr(text) {
    return text.split('\n').map(line => (
        <React.Fragment key={line}>
            {line}
            <br />
        </React.Fragment>
    ));
}

/**
 * Converts a valid JSON object into a standard formatted string
 * @param {json} text
 * @returns {string}
 */
export const jsonToFormattedString = jsonOb => JSON.stringify(jsonOb, null, 4);

/**
 * Returns the string without the dynamic values instead of placeholders
 * @param {string} str the full string to replace {} with right values
 * @param {object} values the values to replace in the full string {key: value}
 * The key need to match the text inside placeholders
 *
 * @returns {string} The string with the text instead of { } placeholders
 */
export const replacePlaceholders = (str = '', values = {}) => {
    if (!values || typeof str !== 'string') {
        return str;
    }

    return Object.keys(values).reduce(
        (carry, key) => carry.replace(`{${key}}`, values[key]),
        str
    );
};

/**
 * Splits a string into three parts based on an opening and ending delimiter
 * @param {string} string Message to split into three parts
 * @param {string} startDelimiter Character that starts the central part
 * @param {string} endDelimiter Character that ends the central part
 *
 * @returns {Array|null} An array containing the three parts, or null if the string is invalid
 */
export const splitStringByDelimiters = (string, startDelimiter = '[', endDelimiter = ']') => {
    if (!string) {
        return null;
    }
    const startBracketIndex = string.indexOf(startDelimiter);
    const endBracketIndex = string.indexOf(endDelimiter);
    if (startBracketIndex > -1 && endBracketIndex > -1 && endBracketIndex > startBracketIndex) {
        return [
            string.substring(0, startBracketIndex),
            string.substring(startBracketIndex + 1, endBracketIndex),
            string.substring(endBracketIndex + 1)
        ];
    }
    return null;
};

export const isNameMatch = (string, stringWithSpaces) => {
    if (string && stringWithSpaces) {
        return string.normalize() === (stringWithSpaces.replace(/\s+/g, '')).normalize();
    }
    return false;
};
