/* --- Imports --- */

// Dependencies
const {ipcRenderer, remote} = require('electron');
const $ = require('jquery');
const marked = require('marked');
const DOMPurify = require('dompurify');

// Services
const RouteService = require('../../service/route');
const DataService = require('../../service/data');
const UserService = require('../../service/user');


/* --- Override object --- */

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

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

/* --- Loader --- */

function loader () {
    if ($('#page-loader').hasClass('hide')) {
        $('#page-loader').removeClass('hide');
        $('#navbar').addClass('hide');
        if ($('#float-add-btn')) {
            $('#float-add-btn').addClass('hide');
        }
    } else {
        if ($('#float-add-btn')) {
            $('#float-add-btn').removeClass('hide');
        }
        $('#navbar').removeClass('hide');
        $('#page-loader').addClass('hide');
    }
};

/* --- Cookie --- */

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;`;
    }
}

/* --- URL Parameter --- */

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];
}