import DOMPurify from 'dompurify';
import Cookies from 'js-cookie';

export const goToUrl = url => window.location.assign(url);
export const parseToBool = (...args) => args.map(arg => arg === true || arg === 'true');

/**
 * Checks if an integer is odd or not
 * @param {number} number - The integer to check
 * @returns {bool}
 */
export const isOdd = number => (number % 2 !== 0);

/**
 * Returns the least common multiple of two numbers
 * @param {number} a integer, will be rounded if not
 * @param {number} b integer, will be rounded if not
 * @returns {number}
 */
export const leastCommonMultiple = (a, b) => {
    const smallest = Math.round(Math.min(a, b));
    const largest = Math.round(Math.max(a, b));
    let i = largest;
    while (i % smallest) {
        i += largest;
    }
    return i;
};

/**
 * Returns a unique ID for the key attribute in map method
 * @param {array} array list of text to join and populate the uid
 * @returns {string}
 */
export const generateUniqueID = array => {
    if (!array || !Array.isArray(array)) {
        return array;
    }

    return array.join('-').toLowerCase().replace(/\s|\//g, '');
};

export const getCookieValue = name => {
    const sanitizedName = DOMPurify.sanitize(name);
    const result = document.cookie.match(`(^|;)\\s*${sanitizedName}\\s*=\\s*([^;]+)`);
    return result ? result.pop() : '';
};

/**
 * Convert a BCP47 locale string format to a Java locale string format
 * @param {string} locale - BCP47 locale string format
 */
export const convertToJavaLocale = locale => {
    const regex = /-/gi;
    return locale.replace(regex, '_');
};

/**
 * Checks if the current session is in SFB preview mode
 * @returns {boolean} true if in SFB preview mode
 */
export function isInPreviewMode() {
    const previewCookie1 = Cookies.get('AppDirect-Preview-Banner-HeartBeat');
    const previewCookie2 = Cookies.get('AppDirect-Product-Preview');
    const builderPreviewCookie = Cookies.get('AppDirect-Builder-Preview-HeartBeat');

    const inPreview = !!previewCookie1 || !!builderPreviewCookie || !!previewCookie2;

    return inPreview;
}
