

/**
 * Generate a unique id
 */
window.genid = window.genid | 0;
export function uid() {
    return window.genid++;
}


export function htmlEncode(str) {
    var i = str.length,
    aRet = [];

    while (i--) {
        var iC = str[i].charCodeAt();
        if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
            aRet[i] = '&#'+iC+';';
        } else {
            aRet[i] = str[i];
        }
    }
    return aRet.join('');  
}

export function decodeHtmlEntities(string) {
    let tmp = document.createElement('textarea');
    
    // Decode html entities
    tmp.innerHTML = string; 
    return tmp.textContent;
}

export function copyToClipBoard(element, successMessage = '', errorMessage = '', nullMessage = '') {
    let el = document.getElementById(element);

    if (el === null) {
        return;
    }
    let value = el.value;

    navigator.clipboard.writeText(value)
        .then(function() {
            // alert('Texte copié');
        })
        .catch(function(error) {
            // alert('Erreur copy : '+error);
        });
}

export function buttonCopyToClipboard(text, button) {
    navigator.clipboard.writeText(text)
    .then(function() {
        // Play/replay animation
        button.classList.remove('anim-btn-flash');
        setTimeout(() => {
            button.classList.add('anim-btn-flash');
        },100);
    });
}

export function indexBy(list, path) {
    return list.reduce((map, obj) => {
        const key = typeof path === 'string' ? obj[path] : path.call(obj);
        map[key] = obj;
        return map;
    }, {});
}

export function getInputByName(name, parent = null) {
    return (parent ?? document).querySelector('[name="'+CSS.escape(name)+'"]');
}

export function roundNumber(value, decimals) {
    const result = Number(Math.round(value + "e" + decimals) + "e-" + decimals);
    return result.toFixed(decimals);
}
