jQuery(() => {

    var token = jQuery("#token").attr("name");
    let category = null;
    let markersFetch = null;
    let categories = null;
    let departements = null;
    let activites = null;

    let articleAfterActivate = null;
    var active = [];
    let group = null;
    var listeProjets = L.control();
    var geom_temp = null;

    let markersExperience = null;
    let markersSIAE = null;
    let markersDT = null;

    // INIT MAP
    var map = L.map('mapid').setView([43.821871, 2.245650], 7.5);


    L.tileLayer('https://api.mapbox.com/styles/v1/dgtnarmelle/cl6vzlpvx000f14upjewi4mfl/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 13,
        minZoom: 7,
        tileSize: 512,
        zoomOffset: -1,
        accessToken: accessToken,
    }).addTo(map);

    // INIT SIDEBAR
    var sidebar = L.control.sidebar('sidebar', {
        position: 'right',
        closeButton: 'true',
        autoPan: 'false'
    });
    map.addControl(sidebar);


    //Bloque le zoom de la carte lors du scroll
    map.scrollWheelZoom.disable();
    map.on('click', () => {
        map.scrollWheelZoom.enable();
    });
    map.on('mouseout', () => {
        map.scrollWheelZoom.disable();
    });


    // FETCH DATA
    jQuery.ajax({
        data: { [token]: "1", task: "initData", format: "json", type: "categories" },
        async: false,
        success: function (result) {
            //category est un tableau contenant les 3 ids dont nous nous servons pour récupérer les projets par type
            category = result.data;

            // GET markers

            //Markers Expériences
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[0] },
                async: false,
                success: function (result) {
                    markersExperience = result.data;
                },
                error: function () { console.log('ajax call failed'); },
            });

            //Markers SIAE
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[1] },
                async: false,
                success: function (result) {
                    markersSIAE = markersExperience.concat(result.data);
                },
                error: function () { console.log('ajax call failed'); },
            });

            //Markers DT
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "markers", catId: category[2] },
                async: false,
                success: function (result) {
                    //On ajoute tout dans le tableau final unique que l'on appelle markersFetch par soucis de comptabilité avec l'ancien code
                    markersFetch = markersSIAE.concat(result.data);
                    //Maintenant qu'on a tous nos projets on peut les ajouter a la carte
                    //onAdd: C'est la fonction d'initialisation qui est appelée lorsqu'on ajoute cet objet à la carte. 
                    //Elle permet de construire le div HTML qui contiendra la légende. Ce div est associé à la classe CSS info.
                    listeProjets.onAdd = function () {
                        addListOfArticles(markersFetch);
                        return _div;
                    }
                    listeProjets.addTo(map);

                    //On garde la liste de côté pour pouvoir l'afficher lors du clic sur un marker DT
                    markersDT = result.data;
                },
                error: function () { console.log('ajax call failed'); },
            });

            // GET departements
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "departement" },
                async: false,
                success: function (result) {
                    departements = Object.values(JSON.parse(result.data.fieldparams).options);
                },
                error: function () { console.log('ajax call failed'); },
            });
            // GET categorie
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "categorie" },
                async: false,
                success: function (result) {
                    categories = Object.values(JSON.parse(result.data.fieldparams).options);
                },
                error: function () { console.log('ajax call failed'); },
            });
            // GET activite
            jQuery.ajax({
                data: { [token]: "1", task: "initData", format: "json", type: "activite" },
                async: false,
                success: function (result) {
                    activites = Object.values(JSON.parse(result.data.fieldparams).options);;
                },
                error: function () { console.log('ajax call failed'); },
            });
        },
        error: function () { console.log('ajax call failed'); },
    });

    // ajout ou retrait dynamique de classe
    $(document).ready(() => {
        $(".departements h6").click((event) => {
            showHide(".departements img", ".departements > h6 > span.unview", ".departements > h6 > span.view");
        });
        $(".categorie h6").click((event) => {
            showHide(".categorie img", ".categorie > h6 > span.unview", ".categorie > h6 > span.view");
        });
        $(".activite h6").click((event) => {
            showHide(".activite img", ".activite > h6 > span.unview", ".activite > h6 > span.view");
        });
        $(".leaflet-control img").click((event) => {
            var current = $(event.currentTarget);
            if (current.hasClass("active") == true) {
                current.removeClass('active');
            } else {
                current.addClass('active');
            }
        });
    });
    //---EOF ajout ou retrait dynamique de classe

    $(".listeArticles").click((event) => {
        if ($(".listeProjets p").css("display") == 'none') {
            $(".listeProjets p").show();
        } else {
            $(".listeProjets p").hide();
        };
    });

    //---Affichage des panels departements / categories / activites / reset
    var departementsLists = L.control({ position: 'topleft' });
    departementsLists.onAdd = function () {
        var icons = [];
        var departement = "departement";
        iconsTheme(departements, departement, icons);
        var div = L.DomUtil.create('div', 'departements'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span>Départements</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var categoriesLists = L.control({ position: 'topleft' });
    categoriesLists.onAdd = function () {
        var icons = [];
        var categorie = "categorie";
        iconsTheme(categories, categorie, icons);
        var div = L.DomUtil.create('div', 'categorie'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span> Catégorie</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var activiteLists = L.control({ position: 'topleft' });
    activiteLists.onAdd = function () {
        var icons = [];
        var activite = "activite";
        iconsTheme(activites, activite, icons);
        var div = L.DomUtil.create('div', 'activite'), icons;
        div.innerHTML += '<h6><span class="view">+ </span><span class="unview" >&ndash; </span>activite</h6>';
        for (var i = 0; i < icons.length; i++) {
            div.appendChild(icons[i]);
        }
        return div;
    };

    var resetButton = L.control({ position: 'topleft' });
    resetButton.onAdd = function () {
        var div = L.DomUtil.create('div', 'reset');
        div.innerHTML += '<input class="uk-button uk-button-secondary" type="button" value="Reset" >';
        return div;
    };

    departementsLists.addTo(map);
    categoriesLists.addTo(map);
    activiteLists.addTo(map);
    resetButton.addTo(map);
    //---EOF Affichage des panels departements / categories / activites / reset

    //Stop propagation pour les drag'n'drop et les doubles clics. 
    $('.leaflet-control').mouseover(function () {
        map.dragging.disable();
        map.doubleClickZoom.disable()
    })
    $('.leaflet-control').mouseout(function () {
        map.dragging.enable();
        map.doubleClickZoom.enable()
    })

    map.scrollWheelZoom.disable();


    function showHide(test, testunview, testview) {
        if ($(test).css("display") == 'none') {
            $(test).show();
            $(testunview).show();
            $(testview).hide();
        } else {
            $(test).hide();
            $(testunview).hide();
            $(testview).show();
        };
    }

    $(".reset").click((event) => {
        $(".leaflet-control img").removeClass('active');
        map.removeLayer(group);
        sidebar.hide();
        reg_tile_temp.clearLayers();
        initMarkersAndGroup(markersFetch);
        listeProjets.onAdd = function () {
            addListOfArticles(markersFetch);
            return _div;
        }
        map.addLayer(group);
        listeProjets.addTo(map);
        $(".listeArticles").click((event) => {
            if ($(".listeProjets p").css("display") == 'none') {
                $(".listeProjets p").show();
            } else {
                $(".listeProjets p").hide();
            };
        });
    });

    $(".leaflet-control:not(.reset , .listeProjets)").click((event) => {
        var arrayActiveDpt = $('.departements img').hasClass('active');
        var arrayActiveCtg = $('.categorie img').hasClass('active');
        var arrayActiveAct = $('.activite img').hasClass('active');

        active = []
        var activeDepartement = document.getElementsByClassName("active");
        for (i = 0; i < activeDepartement.length; i++) {
            active.push(activeDepartement[i].id);
        };
        if (active.length == 0) {
            map.removeLayer(group);
            sidebar.hide();
            reg_tile_temp.clearLayers();
            initMarkersAndGroup(markersFetch);
            listeProjets.onAdd = function () {
                addListOfArticles(markersFetch);
                return _div;
            }
            map.addLayer(group);
            listeProjets.addTo(map);
        } else {
            reg_tile_temp.clearLayers();

            var articlesByDepartement = [];
            var articlesByCategories = [];
            var articlesByActivites = [];
            var arrayOfArticlesByDepartement = [];
            var arrayOfArticlesByCategories = [];
            var arrayOfArticlesByActivites = [];
            var departements = "departement";
            var categories = "categorie";
            var activites = "activite";

            //--- articles en fonction theme
            for (article = 0; article < markersFetch.length; article++) {
                articlesByTheme(articlesByDepartement, departements, arrayOfArticlesByDepartement);
                articlesByTheme(articlesByCategories, categories, arrayOfArticlesByCategories);
                articlesByTheme(articlesByActivites, activites, arrayOfArticlesByActivites);
            }
            //---EOF articles en fonction theme

            //--- comparaison des tableaux et logique OU au sein d'un meme catégorie et ET entre les catégories
            articleAfterActivate = [];

            if ((arrayActiveAct == false && arrayActiveCtg == false) || (arrayActiveDpt == false && arrayActiveAct == false) || (arrayActiveDpt == false && arrayActiveCtg == false)) {
                articleAfterActivate = arrayOfArticlesByDepartement.concat(arrayOfArticlesByCategories).concat(arrayOfArticlesByActivites);
            }
            // ABD for articleByDepartement - ABC for articleByaCategories - ABA for articleByActivites                
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByCategories.length != 0) {
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABC in arrayOfArticlesByCategories) {
                        if (arrayOfArticlesByDepartement[ABD].id.indexOf(arrayOfArticlesByCategories[ABC].id) != '-1') {
                            articleAfterActivate.push(arrayOfArticlesByDepartement[ABD]);
                        }
                    }
                }
            }
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0) {
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABA in arrayOfArticlesByActivites) {
                        if (arrayOfArticlesByDepartement[ABD].id.indexOf(arrayOfArticlesByActivites[ABA].id) != '-1') {
                            articleAfterActivate.push(arrayOfArticlesByDepartement[ABD]);
                        }
                    }
                }
            }
            if (arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) {
                for (let ABA in arrayOfArticlesByActivites) {
                    for (let ABC in arrayOfArticlesByCategories) {
                        if (arrayOfArticlesByActivites[ABA].id.indexOf(arrayOfArticlesByCategories[ABC].id) != '-1') {
                            articleAfterActivate.push(arrayOfArticlesByActivites[ABA]);
                        }
                    }
                }
            }
            if ((arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0 && arrayActiveCtg == true && arrayOfArticlesByCategories.length == 0) || (arrayOfArticlesByDepartement.length == 0 && arrayActiveDpt == true && arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) || (arrayOfArticlesByDepartement.length != 0 && arrayActiveAct == true && arrayOfArticlesByActivites.length == 0 && arrayOfArticlesByCategories.length != 0)) {
                articleAfterActivate = [];
            }
            if (arrayOfArticlesByDepartement.length != 0 && arrayOfArticlesByActivites.length != 0 && arrayOfArticlesByCategories.length != 0) {
                var temporaryArticle = [];
                function ObjCompare(obj1, obj2, obj3) {
                    if (obj1.id === obj2.id && obj2.id === obj3.id && obj1.id === obj3.id) {
                        return true;
                    };
                }
                for (let ABD in arrayOfArticlesByDepartement) {
                    for (let ABA in arrayOfArticlesByActivites) {
                        for (let ABC in arrayOfArticlesByCategories) {
                            if (ObjCompare(arrayOfArticlesByDepartement[ABD], arrayOfArticlesByActivites[ABA], arrayOfArticlesByCategories[ABC]) == true) {
                                temporaryArticle.push(arrayOfArticlesByDepartement[ABD]);
                            }
                        }
                    }
                }
                articleAfterActivate = temporaryArticle;
            }
            //---EOF comparaison des tableaux et logique OU au sein d'un meme catégorie et ET entre les catégories       

            //---Markers et clusters articles actif
            if (articleAfterActivate != markersFetch || articleAfterActivate.length != 0) {
                map.removeLayer(group);
                sidebar.hide();
                map.setView([46, 0], 6);
                initMarkersAndGroup(articleAfterActivate);
                map.addLayer(group);
            }
            if (articleAfterActivate.length == 0) {
                map.removeLayer(group);
                sidebar.hide();
                initMarkersAndGroup(articleAfterActivate);
                map.addLayer(group);
            }
            //---EOF Markers et clusters articles actif

            //---Affichage liste des projets dynamiquee
            if (Object.keys(listeProjets).length > 2) {
                listeProjets.remove(map);
                if (articleAfterActivate.length == 0 && (arrayActiveCtg == true || arrayActiveDpt == true || arrayActiveAct == true)) {
                    listeProjets.onAdd = function () {
                        addListOfArticles(articleAfterActivate);
                        return _div;
                    }
                }
                else if (articleAfterActivate.length == 0) {
                    listeProjets.onAdd = function () {
                        addListOfArticles(markersFetch);
                        return _div;
                    }
                } else {
                    listeProjets.onAdd = function () {
                        addListOfArticles(articleAfterActivate);
                        return _div;
                    }
                }
                listeProjets.addTo(map);
            }
            //--- EOF Affichage liste des projets dynamique
        };

        $(".listeArticles").click(() => {
            if ($(".listeProjets p").css("display") == "none") {
                $(".listeProjets p").show();
            } else {
                $(".listeProjets p").hide();
            };
        });

        $(".close").click(() => {

            $(".listeProjets p").hide();
            $(".listeProjets").show();
        });

    });

    //création d'une couche temporaire pour WKT et permettre le retrait de la zone seule
    reg_tile_temp = new L.layerGroup().addTo(map);

    //---Markers and Cluster
    const markerIcon = L.icon({
        iconSize: [25, 41],
        iconAnchor: [10, 41],
        popupAnchor: [2, -40],
        iconUrl: 'https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png',
        shadowUrl: 'https://unpkg.com/leaflet@1.4.0/dist/images/marker-shadow.png'
    });

    var LeafIcon = L.Icon.extend({
        options: {
            shadowUrl: 'https://unpkg.com/leaflet@1.4.0/dist/images/marker-shadow.png',
            iconSize: [25, 41],
            iconAnchor: [10, 41],
            popupAnchor: [2, -40]
        }
    });
    var orangeIcon = new LeafIcon({ iconUrl: 'https://eolab.cnes.fr/images/Projets/icon_orange.png' });


    initMarkersAndGroup(markersFetch);
    map.addLayer(group);
    //---EOF Markers and Cluster

    /* A remettre et retravailler pour images filtres departements */
    function iconsTheme(dataOfTheme, nameOfTheme, icons) {
        dataOfTheme.forEach((theme) => {
            var img = document.createElement("IMG");
            img.setAttribute("src", `${window.location.origin}/images/cartographie/${nameOfTheme}/${theme.value}.png`);
            img.setAttribute("width", "40px");
            img.setAttribute("height", "40px");
            img.setAttribute("style", "margin-right: 10px;margin-top: 10px;");
            img.setAttribute("id", theme.value);
            img.setAttribute("title", theme.name);
            icons.push(img);
        })
    } 

    function addListOfArticles(article) {
        _div = L.DomUtil.create('div', 'listeProjets'), article;
        _div.innerHTML = `<div class=listeArticles><h3><span uk-icon="menu"></span> Liste (<span class="nombreProjetsAffiches">` + article.length + `</span>)</h3></div>`;
        for (var i = 0; i < article.length; i++) {
            _div.innerHTML += `<p style="display: none;"><a href="${window.location.origin}/projets/${article[i].alias}" target="_blank">` + article[i].title + `</a></p>`;
        }
    }

    function articlesByTheme(articlesBy, nameOfTheme, arrayOfArticleBy) {
        if (markersFetch[article][nameOfTheme] != null) {
            articlesBy.push(markersFetch[article]);
            for (let article in articlesBy) {
                for (let a in active) {
                    for (let test in articlesBy[article][nameOfTheme]) {
                        if (articlesBy[article][nameOfTheme][test] == (active[a])) {
                            if (arrayOfArticleBy.includes(articlesBy[article]) == false) {
                                arrayOfArticleBy.push(articlesBy[article]);
                            }
                        }
                    }
                }
            }
        }
    }
    function displayListOfArticlesOnSidebarClosed() {
        $(".close").click(() => {

            $(".listeProjets p").hide();
            $(".listeProjets").show();
        });

    }

    //Fonction qui vérifie si l'état du champs contenant la chaîne WKT de la zone d'intérêt des projets. 
    function checkInterestZone(zone) {
        if (zone == null) {
            return false;
        } else {
            return true;
        }
    }

    function initMarkersAndGroup(items) {
        group = new L.markerClusterGroup({ showCoverageOnHover: false, zoomToBoundsOnClick: true,  spiderfyOnMaxZoom: false, disableClusteringAtZoom : 8});
       
        for (let article = 0; article < items.length; article++) {
            var articleMarker = items[article].localisation;
            // mise au format des coordonnées pour affichage avec L.marker
            var coordArticleMarker = articleMarker.split(',');
            let lat = coordArticleMarker[0];
            let long = coordArticleMarker[1];
            let title = items[article].title;
            
            var _mar = L.marker(new L.LatLng(lat, long), {
                icon: markerIcon
            });
            
            _mar.bindPopup(title);
            _mar.on('click', function clicMarker() {
                $(".listeProjets").hide();
                const _marActive = L.marker(new L.LatLng(lat, long), {
                   icon: orangeIcon
                  });
                
                //Récupérer les coordonnées du point, stocker dans une variable (appelée dans la sidebar.setContent plus bas)                    
                sidebar.show();

                //Vérifier si marqueur est de type DT ou autres
                //On se base sur nomdelasiae car le champ n'est pas présent sur les projets DT mais est présent sur les autres
                if (items[article].nomdelasiae == null)
                {
                   content = `<div class="listeProjetsDT">
                            <div class=listeArticles>
                            <h3 class="uk-heading-medium">
                            <span uk-icon="icon: menu; ratio: 2" class="uk-icon"></span> Liste (<span class="nombreProjetsAffiches">${markersDT.length}</span>)
                            </h3>
                            </div>`;
                    for (var i = 0; i < markersDT.length; i++) {
                        content += `<p>
                                    <a href="${window.location.origin}/projets/${markersDT[i].alias}" target="_blank">` + markersDT[i].title + `</a>
                                    </p>`;
                    }
                    content += `</div>`;
                            
                } else {
                    content = `<h3 class="uk-heading-medium">${title}</h3> <br/>
                            <div class="uk-text-lead uk-margin-bottom">${items[article].introtext} </div>
                            <a class="uk-button uk-button-primary" href="${window.location.origin}/projets/${items[article].alias}" target="_blank"><span uk-icon="table"></span>Voir l'article complet</a>`;
                }
                sidebar.setContent(content);
                sidebar.on('close', displayListOfArticlesOnSidebarClosed());
                
                //Remet reg_tile_temp à 0 avant d'y intégrer geom_temp si le champs contenant le WKT de la zone d'intérêt est complété 
                reg_tile_temp.clearLayers();
                var zoneDefined = checkInterestZone(items[article].jce);
                if (zoneDefined) {
                    geom_temp = omnivore.wkt(items[article].jce);
                    //console.log("geom_temp " + geom_temp);
                    // reg_tile_temp.clearLayers();
                    geom_temp.addTo(reg_tile_temp);
                }
                _marActive.addTo(reg_tile_temp);
               
            });
            if (map.getZoom() > 15 && map.hasLayer(_mar)) {
                map.closePopup();
            }
  
            group.addLayer(_mar);
            
        }
    }
});
