import AppConfigStore from '../stores/AppConfigStore';

/**
 * Librairie de fonctions utilitaires diverses.
 *
 * @module
 */

/**
 * Returns a function, that, as long as it continues to be invoked, will not
 * be triggered. The function will be called after it stops being called for
 * N milliseconds. If `immediate` is passed, trigger the function on the
 * leading edge, instead of the trailing.
 *
 * Credit David Walsh (https://davidwalsh.name/javascript-debounce-function)
 */
export function debounce(func, wait, immediate) {
    var timeout;

    // This is the function that is actually executed when
    // the DOM event is triggered.
    return function executedFunction() {
        // Store the context of this and any
        // parameters passed to executedFunction
        var context = this;
        var args = arguments;

        // The function to be called after
        // the debounce time has elapsed
        var later = function () {
            // null timeout to indicate the debounce ended
            timeout = null;

            // Call function now if you did not on the leading end
            if (!immediate) func.apply(context, args);
        };

        // Determine if you should call the function
        // on the leading or trail end
        var callNow = immediate && !timeout;

        // This will reset the waiting every function execution.
        // This is the step that prevents the function from
        // being executed because it will never reach the
        // inside of the previous setTimeout
        clearTimeout(timeout);

        // Restart the debounce waiting period.
        // setTimeout returns a truthy value (it differs in web vs node)
        timeout = setTimeout(later, wait);

        // Call immediately if you're dong a leading
        // end execution
        if (callNow) func.apply(context, args);
    };
}

/**
 * Teste si le stockage locale (localStorage) est disponible.
 * @returns {boolean} true si disponible, false sinon
 */
export function testLocalStorageAvailable() {
    var test = 'testLocalStorage';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch (e) {
        return false;
    }
}

/**
 * Renvoie la valeur d'un cookie de nom donné ou null si absent.
 * @param {string} name - Nom du cookie
 * @returns
 */
export function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        let cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            let cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === name + '=') {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

/**
 * Renvoie les mails des gestionnaires associés aux sous-viviers identifiés par leur id.
 * @param {AppConfigStore} appConfig
 * @param {array} svids - Ids des sous-viviers
 * @returns {array} liste des mails
 */
export const getEmails = (appConfig, svids) => {
    var mails = [];
    const data_mails = appConfig.donneesReference.sousViviers;
    const all_sv = data_mails.map(a=>a.sv_id)
    svids.map((a) => {if (all_sv.includes(a)) {
        mails.push(...data_mails.filter( element => element.sv_id == a)[0].gestionnaires)}})
    var unique_mails = Array.from(new Set(mails));
    unique_mails = unique_mails.filter(data => (data != "" && data!=appConfig.utilisateurConnecte?.email))
    return unique_mails;
};

/**
 * Envoie un mail aux personnes identifiés par leurs adresses mails pour indiquer le changement de sous-vivier d'un administré
 * @param {array} emailTo - Liste des adresses mails destinataires
 * @param {array} emailCC - Liste des adresses mails en copie
 * @param {array} svids - Id du sous-vivier de destination
 * @param {Object} administre - Objet contenant les données issues du backend pour chaque administré
 * @returns
 */
export const sendMail = (emailTo, emailCC, svid, administre) => {
    emailCC = emailCC.filter( x => !emailTo.includes(x) )
    const emailToJoined = emailTo.join(';');
    const emailCCJoined = emailCC.join(';');
    const emailSub = "[OGURE NG] Transfert d’administré entre sous-viviers"
    const emailBody = "Les administrés suivants ont été transférés dans le sous-vivier %20" + svid + " : %0D%0A" + administre.map(a=>(a.identite_grade_nom_prenom + ' (ID SAP : %20' + a.identite_matricule + ')')).join('%0D%0A')

    if (emailCCJoined) {
        return (window.location = "mailto:"+emailToJoined+'?cc='+emailCCJoined+'&subject='+emailSub+'&body='+emailBody);
    }
    else {
        return (window.location = "mailto:"+emailToJoined+'?subject='+emailSub+'&body='+emailBody);
    }
}

/**
 * Permet d'obtenir l'id du sous-vivier associé à un domaine, filière, nf
 * @param {string} dom - Id du domaine
 * @param {string} fil - Id de la filière
 * @param {string} nf - Id du niveau fonctionnel
 * @returns {array} Array contenant l'id du sous-vivier
 */
export const getSVId = (dom,fil,nf) => {
    const list_mdr  = ['1A', '1B', '1C'];
    const list_soff = ['2.', '3A', '3B', '3B NFS'];
    const list_off  = ['4.', '5A', '5B', '5C', '6A', '6B'];
    var cat = 'ze';
    if (list_mdr.includes(nf)) {
        cat = 'MDR';
    }
    else if (list_soff.includes(nf)) {
        cat = 'SOFF';
    }
    else if (list_off.includes(nf)) {
        cat = 'OFF';
    }
    const SvId = [dom + ', ' + fil + ', ' + cat];
    return SvId
}
