/* --- Surcharge objets --- */

String.prototype.capitalize = function() {
    return this[0].toUpperCase() + this.slice(1);
}

/* --- Fonctions utilitaires --- */

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 pagination(id, pageNum, perPage, total, tabElt, paginationElt, dataPage, tableClass, last) {
    pageNum = parseInt(pageNum);
    perPage = parseInt(perPage);
    total = parseInt(total);
    tableClass = tableClass || 'striped';
    if (pageNum < 1) {
    	pageNum = 1;
    }
    // Création du tableau
    let tab = `<table id="pagination-${id}-table" class="${tableClass}">`;
    let first = true;
    let keys = [];
    dataPage.forEach(elt => {
        if(first) {
            tab += '<thead><tr>';
            let lastKey;
            for (const key in elt) {
            	// Garde la derniere clef pour la fin
            	if (last != key) {
            		keys.push(key);
                    tab += `<th>${key.capitalize()}</th>`;
            	} else {
            		lastKey = key;
            	}
            }
            // Si il y a une derniere clef on l'ajoute
            if (lastKey) {
            	keys.push(lastKey);
                tab += `<th>${lastKey.capitalize()}</th>`;
            }
            tab += '</tr></thead><tbody>';
            first = false;
        }
        tab += '<tr>';
        keys.forEach(key => {
        	// Garde la valeur de la derniere clef pour la fin
        	if (last != key) {
        		tab += `<td style="width: ${Math.round((1/keys.length)*100)}%;">${elt[key]}</td>`;
        	}
        });
        // Ajoute la valeur de la derniere clef
        if (last && keys.indexOf(last) !== -1) {
        	tab += `<td style="width: ${Math.round((1/keys.length)*100)}%;">${elt[last]}</td>`;
        }
        tab += '</tr>';
    });
    tab += '</tbody></table>';
    // Creation de la pagination
    const nbPage = Math.ceil(total / perPage);
    if (pageNum > nbPage) {
    	// Si il n' y a pas assez de page pour aller à la page demandé on va au maximum
    	pageNum = nbPage
    }
    let pagination = `<ul class="pagination" data-active="${pageNum}">`;
    if(pageNum == 1) {
        pagination += '<li class="disabled"><span><i class="material-icons">chevron_left</i></span></li>';
    } else {
        pagination += `<li class="waves-effect"><span class="pagination-${id}-prev" data-page="${pageNum - 1}"><i class="material-icons">chevron_left</i></span></li>`;
    }
    for(let i = 1; i <= nbPage; i++) {
        if(pageNum === i) {
            pagination += `<li class="active"><span>${i}</span></li>`;
        } else {
            pagination += `<li class="waves-effect"><span class="pagination-${id}-number" data-page="${i}">${i}</span></li>`;
        }
    }
    if(pageNum == nbPage || total == 0) {
        pagination += '<li class="disabled"><span><i class="material-icons">chevron_right</i></span></li>';
    } else {
        pagination += `<li class="waves-effect"><span class="pagination-${id}-next" data-page="${pageNum + 1}"><i class="material-icons">chevron_right</i></span></li>`;
    }
    pagination += '</ul>';
    // Affichage
    tabElt.html(tab);
    paginationElt.html(pagination);
    // Retourne la page courante
    return pageNum;
}

/* --- Initialisation modules --- */

$(document).ready(function(){
    
    // Chargement menu mobile
    $('.sidenav').sidenav();
    // Select
    $('select').formSelect();
    // Tooltip
    $('.tooltipped').tooltip();
    // Tabs
    $('.tabs').tabs();
    // Modal
    M.Modal.init($('.popup'), {
        dismissible: false,
        startingTop: '30%',
        endingTop: '35%',
        onOpenEnd: (modal) => {
            setTimeout(() => { 
                M.Modal.getInstance(modal).close();
            }, 1500);
        }
    });
    M.Modal.init($('.loader'), {
        dismissible: false,
        startingTop: '30%',
        endingTop: '35%'
    });
    M.Modal.init($('.conf'), {
        dismissible: true,
        startingTop: '30%',
        endingTop: '35%'
    });
    // Date picker
    M.Datepicker.init($('.datepicker'), {
        format: 'dd/mm/yyyy',
        firstDay: 1,
        yearRange: [
            new Date(Date.now()).getFullYear() - 100,
            new Date(Date.now()).getFullYear()
        ],
        i18n: {
            cancel: 'Annuler',
            clear: 'Supprimer',
            months: [
                'Janvier',
                'Fevrier',
                'Mars',
                'Avril',
                'Mai',
                'Juin',
                'Juillet',
                'Aout',
                'Septembre',
                'Octobre',
                'Novembre',
                'Decembre'
            ],
            monthsShort: [
                'Janv',
                'Fevr',
                'Mars',
                'Avr',
                'Mai',
                'Juin',
                'Juil',
                'Aout',
                'Sept',
                'Oct',
                'Nov',
                'Dec'
            ],
            weekdays: [
                'Dimanche',
                'Lundi',
                'Mardi',
                'Mercredi',
                'Jeudi',
                'Vendredi',
                'Samedi'       
            ],
            weekdaysShort: [
                'Dim',
                'Lun',
                'Mar',
                'Mer',
                'Jeu',
                'Ven',
                'Sam'
            ],
            weekdaysAbbrev:	['D','L','M','M','J','V','S']
        }
    });
    
    // Affichage des erreur struts
    $('.field-error').each(function() {
    	const error = $(this).children('ul li').children('span').html();
    	const parent = $(this).parent();
        parent.children('.helper-text').attr('data-error', error);
        parent.children('.validate').addClass('invalid');
    });
    
    // Cookie consent
    window.cookieconsent.initialise({
    	palette: {
    		popup: {
    			background: "#aa0000",
    			text: "#ffdddd"
    	    },
    	    button: {
    	    	background: "#ff0000"
    	    }
    	  },
    	  position: "bottom-right",
    	  content: {
    		  message: "Ce site web utilise des cookies pour améliorer votre expérience de navigation. En continuant sur ce site vous acceptez leurs utilisations.",
    		  dismiss: "Accepter",
    		  link: "En savoir plus"
    	  }
    });
});