/** * Transform markdown string to html */ String.prototype.toHTML = function() { return DOMPurify.sanitize( marked(this.toString()) .replace(/
/g, '
')
    );
}

Array.prototype.removeItem = function(item) {
    const index = this.indexOf(item);
    if (index !== -1) {
        this.splice(index, 1);
    }
    return this;
}

function getCookie(key) {
    const split = document.cookie.split(';');
    let cookies = {};
    split.forEach(elt => {
        const val = elt.trim().split('=');
        cookies[val[0]] = val[1];
    });
    if(key !== undefined) {
        return cookies[key];
    }
    return cookies;
}

function removeCookie(key) {
    if (Array.isArray(key)) {
        key.forEach(elt => {
            removeCookie(elt);
        });
    } else {
        document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
    }
}

function parseURLParameter() {
    const data = {};
    const get = location.search.substr(1).split("&");
    for (elt of get) {
        const split = elt.split("=");
        data[split[0]] = decodeURIComponent(split[1]);
    }
    return data;
}

function getURLParameter(key) {
    const get = parseURLParameter();
    return get[key];
}

/**
 * Load all card
 * @param boolean toArray (optionnal) send result in array and not in object (default: false)
 */
function loadData(toArray) {
    toArray = toArray ? toArray : false;
    const data = toArray ? [] : {};
    return new Promise(resolve => {
        // Data already load
        if (localStorage.list) {
            const list = JSON.parse(localStorage.list);
            for (element of list) {
                toArray ? data.push(JSON.parse(localStorage.getItem(element))) : data[element] = JSON.parse(localStorage.getItem(element));
            }
            resolve(data);
        } 
        // Load data on server
        else {
            const list = [];
            $.getJSON('data/list.json', (file) => {
                const total = file.length;
                let count = 0;
                file.forEach(element => {
                    $.getJSON(`data/${element}.json`, (result) => {
                        toArray ? data.push(result) : data[result.id] = result;
                        list.push(result.id);
                        localStorage.setItem(result.id, JSON.stringify(result));
                        if (++count === total) {
                            localStorage.setItem('list', JSON.stringify(list));
                            resolve(data);
                        }
                    });
                });
            });
        }
    });
}

function uniqId() {
    return '_' + Math.random().toString(36).substr(2, 9);
}