/*
 * Copyright 2019 - All rights reserved.
 * Rodrigo Tapia-McClung
 *
 * August-September 2019
 */

/* global Promise, omnivore, JSZip, map, layerControl, updateCharts */
/* exported makeBaseMap, baseLayerPromises, drawnItems */

let baseLayerPromises = [],
    drawnItems;

// function to read compressed json and create a leaflet layer
const zip2Lyr = (zipFile, layerName, layerTemplate) => {
    baseLayerPromises.push(
        new Promise( (resolve, reject) => {
            fetch(zipFile) // 1) fetch the url
                .then( response => { // 2) filter on 200 OK
                    if (response.status === 200 || response.status === 0) {
                        return Promise.resolve(response.blob());
                    } else {
                        return Promise.reject(new Error(response.statusText));
                    }
                })
                .then(JSZip.loadAsync) // 3) chain with the zip promise
                .then(zip => {
                    let filename = Object.keys(zip.files)[0];
                    let filetype = filename.split(".").pop();
                    return [zip.file(filename), filetype]; // 4) chain with the text content promise
                })
                .then( ([file, type]) => {
                    file.async("string").then(
                        function success(text) { // 5) display the result
                            if (type == "json") {
                                layerTemplate.addData(JSON.parse(text));
                            } else if (type == "topojson") {
                                layerName = omnivore.topojson.parse(text, null, layerTemplate);
                            }
                            resolve("done");
                        }, function error(e) {
                            console.log(e);
                            reject("error");
                        }
                    );
                });
        })
    );
}

const createPane = (layerPane, zIndex) => {
    map.createPane(layerPane);
    map.getPane(layerPane).style.zIndex = zIndex;
    map.getPane(layerPane).style["mix-blend-mode"] = "normal";
}

const getSchoolColor = s => {
    return s == "Básico" ? "#409400" :
        s == "Medio superior" ? "#df6400" :
            "#c0d1e5";
}

let escuelas, hospitales, hoteles,  puentes, puntoFronterizo, descargas, presas, subcuencas, tuxtlaVH, zms, anps;

//  *** WMS INEGI ***
// AGEBS RURAL
let agebrur = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c108",
    format: "image/svg+xml",
    transparent: true,
    attribution: "INEGI 2019"
});
// AGEBS URBANO
let ageburb = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c109",
    format: "image/svg+xml",
    transparent: true,
    attribution: "INEGI 2019"
});
let layer_agebswms = L.layerGroup([agebrur, ageburb],{
    pane: "pane_agebs",
    minZoom:11,
    maxZoom:18
});
// NOMBRES DE CUERPOS DE AGUA
let layer_nombresWB = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "t311",
    format: "image/svg+xml",
    transparent: true,
    attribution: "INEGI 2019",
    minZoom:9,
    pane: "pane_wbnames"
});
//RED NACIONAL DE CAMINOS
let layer_RedNacionalCaminos= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "RNC", //Red nacional de caminos
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_carreteras",
    attribution: "INEGI 2019"
});
//MANZANAS
let layer_manzanaswms= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c104",
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_manzanas",
    attribution: "INEGI 2019",
    minZoom:13,
    maxZoom:18
});
//LOCALIDAD URBANA
let layer_locUrban= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c102",
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_locs",
    attribution: "INEGI 2019"
});
//Límite geoestadístico municipal
let layer_limiteMunicipal= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c101",  //Límite geoestadístico municipal
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_munis",
    attribution: "INEGI 2019",
    minZoom:9
});
//  Area verde urbana -- camellones?
let layer_areaVerdeUrbana= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
    layers: "c110",  //Límite geoestadístico municipal
    format: "image/svg+xml",
    transparent: true,
    pane: "pane_camellones",
    attribution: "INEGI 2019",
    minZoom:11,
    maxZoom:18
});
//  *** FIN WMS INEGI ***

let layer_escuelas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_escuelas",
    pointToLayer: (feature, latlng) => {
        let escuelaMarker = L.BeautifyIcon.icon({
            icon: "escuela",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 15px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: getSchoolColor(feature.properties["Nivel"])
        });
        return new L.Marker(latlng, {
            icon: escuelaMarker
        });
    }
});

let layer_hospitales = new L.geoJson(null, {
    attribution: "",
    pane: "pane_hospitales",
    pointToLayer: (_feature, latlng) => {
        let hospitalMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 13px;",
            html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#ff0000;\"></i><i class =\"fas fa-plus-circle fa-stack-1x fa-inverse\"></i></span>",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#C0C0C0"
        });
        return new L.Marker(latlng, {
            icon: hospitalMarker
        });
    }
});

let layer_hoteles = new L.geoJson(null, {
    attribution: "",
    pane: "pane_hoteles",
    pointToLayer: (_feature, latlng) => {
        let hotelMarker = L.BeautifyIcon.icon({
            icon: "bed",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 12px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#808080"
        });
        return new L.Marker(latlng, {
            icon: hotelMarker
        });
    }
});

let layer_puentes = new L.geoJson(null, {
    attribution: "",
    pane: "pane_puentes",
    pointToLayer: (_feature, latlng) => {
        let puenteMarker = L.BeautifyIcon.icon({
            icon: "puente",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 12px; transform: rotate(45deg);",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#808080"
        });
        return new L.Marker(latlng, {
            icon: puenteMarker
        });
    }
});

let layer_puerto = new L.geoJson(null, {
    attribution: "",
    pane: "pane_puerto",
    pointToLayer: (_feature, latlng) => {
        let puertoMarker = L.BeautifyIcon.icon({
            icon: "puertoindustrial",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 20px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "grey"
        });
        return new L.Marker(latlng, {
            icon: puertoMarker
        });
    }
});

let layer_frontera = new L.geoJson(null, {
    attribution: "",
    pane: "pane_frontera",
    styles: null,
    pointToLayer: (_feature, latlng) => {
        let fronteraMarker = L.BeautifyIcon.icon({
            icon: "puntofronterizo",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 14px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#808080"
        });
        return new L.Marker(latlng, {
            icon: fronteraMarker
        });
    }
});

let layer_descargas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_descargas",
    pointToLayer: (_feature, latlng) => {
        let descargasMarker = L.BeautifyIcon.icon({
            icon: "desechos",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size: 8px; transform: rotate(45deg); opacity:0.75;",
            borderWidth: 0,
            borderColor: "black",
            backgroundColor: "transparent",
            textColor: "#808080"
        });
        return new L.Marker(latlng, {
            icon: descargasMarker
        });
    }
});

let layer_presas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_presas",
    pointToLayer: (_feature, latlng) => {
        let presasMarker = L.BeautifyIcon.icon({
            icon: "presa",
            iconSize: [0, 0],
            iconAnchor: [7, 10],
            iconShape: "circle",
            popupAnchor: [0, 0],
            innerIconStyle: "font-size:16px;",
            borderWidth: 0,
            borderColor: "transparent",
            backgroundColor: "transparent",
            textColor: "#808080"//"#123fb8"
        });
        return new L.Marker(latlng, {
            icon: presasMarker
        });
    }
});

const style_cuencas = () => {
    return {
        pane: "pane_cuencas",
        opacity: 1,
        color: "rgba(0,0,0,0.25)",
        dashArray: "",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fill: true,
        fillOpacity: 1,
        fillColor: "rgba(213,190,245,0.25)"
    }
}

let layer_cuencas = new L.geoJson(null, {
    attribution: "",
    pane: "pane_cuencas",
    style: style_cuencas
});

const style_limZMs = () => {
    return {
        pane: "pane_limZMs",
        opacity: 1,
        color: "rgba(101,43,0,0.6)",
        dashArray: "",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fillOpacity: 0
    }
}

let layer_limZMs = new L.geoJson(null, {
    attribution: "",
    pane: "pane_limZMs",
    style: style_limZMs
});

const style_ZMs = feature => {
    switch (String(feature.properties["ZM_NOMBRE"])) {
    case "Tuxtla Gutiérrez":
        return {
            pane: "pane_ZMs",
            opacity: 1,
            color: "rgba(139,47,0,0.6)",
            dashArray: "",
            lineCap: "butt",
            lineJoin: "miter",
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(139,60,0,0.6)"
        }
    case "Villahermosa":
        return {
            pane: "pane_ZMs",
            opacity: 1,
            color: "rgba(139,47,0,0.6)",
            dashArray: "",
            lineCap: "butt",
            lineJoin: "miter",
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(207,152,62,0.6)"
        }
    }
}

let layer_ZMs = new L.geoJson(null, {
    attribution: "",
    pane: "pane_ZMs",
    style: style_ZMs
});

const style_ANPs = () => {
    return {
        pane: "pane_ANPs",
        opacity: 1,
        color: "#00ff00",
        dashArray: "3 2",
        lineCap: "butt",
        lineJoin: "miter",
        weight: 1.0,
        fill: true,
        fillOpacity: 1,
        fillColor:"rgba(0,240,2,0.05)"
    }
}

let layer_ANPs = new L.geoJson(null, {
    attribution: "",
    pane: "pane_ANPs",
    style: style_ANPs
});

const styleDrawnItems = () => {
    let currentId = 0;
    drawnItems.eachLayer( l => {
        l.feature.properties.id = currentId;
        l.feature.properties.color = d3.schemeCategory10[currentId];

        l.setStyle({
            fillColor: d3.schemeCategory10[currentId],
            opacity: 0.5,
            fillOpacity: 0.2,
            color: d3.schemeCategory10[currentId],
            weight: 4
        });
        currentId++;
    });
}

const toggleButtons = () => {
    let buttons = [];
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-polyline")[0]);
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-polygon")[0]);
    buttons.push(document.getElementsByClassName("leaflet-draw-draw-rectangle")[0]);

    buttons.forEach( b => {
        // disable buttons if there are 10 drawn items
        if (drawnItems.getLayers().length >= 10) {
            b.onClick = "preventEventDefault(); return false";
            b.classList.add("draw-control-disabled");
        // enable buttons if there are less than 10 drawn items
        } else if (drawnItems.getLayers().length < 10) {
            b.onClick = null;
            b.classList.remove("draw-control-disabled");
        }
    });
}

const makeBaseMap = () => {
    createPane("pane_ANPs", 400);
    createPane("pane_munis", 402);
    createPane("pane_ZMs", 403);
    createPane("pane_limZMs", 404);
    createPane("pane_locs", 405);
    createPane("pane_cuencas", 406);
    createPane("pane_buffer", 407);
    createPane("pane_manzanas", 408);
    createPane("pane_presas", 409);
    createPane("pane_descargas", 410);
    createPane("pane_carreteras", 411);
    createPane("pane_frontera", 412);
    createPane("pane_puerto", 413);
    createPane("pane_puentes", 414);
    createPane("pane_casetas", 415);
    createPane("pane_camellones", 416);
    createPane("pane_agebs", 417);
    createPane("pane_hoteles", 418);
    createPane("pane_hospitales", 419);
    createPane("pane_escuelas", 420);
    createPane("pane_wbnames",421);

    layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
    zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas);
    layerControl.addOverlay(layer_escuelas, "Escuelas con 50 personas ocupadas o más<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#409400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Básico<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#df6400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Medio superior<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#c0d1e5;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Otras escuelas");
    zip2Lyr("../grijalva/data/hospitales.zip", hospitales, layer_hospitales);
    layerControl.addOverlay(layer_hospitales, "<span class=\"fa fa-stack\" style=\"padding-top: 6px;\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#ff0000;\"></i><i class=\"fas fa-plus-circle fa-stack-1x fa-inverse\"></i></span>Hospitales con 50 personas ocupadas o más");
    zip2Lyr("../grijalva/data/hoteles.zip", hoteles, layer_hoteles);
    layerControl.addOverlay(layer_hoteles, "&nbsp; <i class=\"fas fa-bed style=\"color:#808080;\"></i> Hoteles principales");
    layerControl.addOverlay(layer_agebswms, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=none stroke=\"#d3d3d3\"></rect></svg><span style=\"font-size=xx-small\">&nbsp;AGEBs 2018</span>");
    layerControl.addOverlay(layer_areaVerdeUrbana, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c110\" alt=\"Áreas verdes urbanas\" />");
    zip2Lyr("../grijalva/data/puentes.zip", puentes, layer_puentes);
    layerControl.addOverlay(layer_puentes, "&nbsp; <i class=\"fa fa-puente\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 10px;\"></i> &nbsp;Puentes");
    let puerto = omnivore.geojson("../grijalva/data/PuertoFrontera.json", null, layer_puerto);
    layerControl.addOverlay(puerto, "&nbsp; <i class=\"fa fa-puertoindustrial\" style=\"margin-top:3px; margin-left:0px;font-size: 12px;\"></i> Puerto");
    zip2Lyr("../grijalva/data/PuntosFrontera.zip", puntoFronterizo, layer_frontera);
    layerControl.addOverlay(layer_frontera, "&nbsp;<i class=\"fa fa-puntofronterizo\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 16px;\"></i> Punto fronterizo");
    layerControl.addOverlay(layer_RedNacionalCaminos, "Red nacional de caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>");
    zip2Lyr("../grijalva/data/descargas.zip", descargas, layer_descargas);
    layerControl.addOverlay(layer_descargas, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#808080;margin-top:3px;margin-left:0px;font-size: 12px;opacity:0.75;\"></i>&nbsp;&nbsp;Descargas residuales municipales e industriales");
    zip2Lyr("../grijalva/data/presas.zip", presas, layer_presas);
    layerControl.addOverlay(layer_presas, "&nbsp; <i class=\"fa fa-presa\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 12px;\"></i> Presas principales");
    layerControl.addOverlay(layer_manzanaswms, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c102m\" alt=\"Manzanas\"/>");
    zip2Lyr("../grijalva/data/cuencas.zip", subcuencas, layer_cuencas);
    layerControl.addOverlay(layer_cuencas, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(213,190,245,0.5)\" stroke=\"rgba(0,0,0,0.25)\" stroke-dasharray=\" \"></rect></svg> Cuenca y subcuencas del Grijalva, CONAGUA 2017");
    layerControl.addOverlay(layer_locUrban, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c102\" alt=\"Localidades urbanas\"/>");
    zip2Lyr("../grijalva/data/limites_TG_V.zip", tuxtlaVH, layer_limZMs);
    layerControl.addOverlay(layer_limZMs, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"none\" stroke=\"rgba(101,43,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Límites de zonas metropolitanas");
    zip2Lyr("../grijalva/data/limitesZM.zip", zms, layer_ZMs);
    layerControl.addOverlay(layer_ZMs, "Zonas metropolitanas<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(139,60,0,0.8)\" stroke=\"rgba(139,47,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Tuxtla Gutiérrez<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(207,152,62,0.8)\" stroke=\"rgba(139,47,0,0.6)\" stroke-dasharray=\" \"></rect></svg> Villahermosa");
    layerControl.addOverlay(layer_limiteMunicipal, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=c101&format=image/png&STYLE=default\" alt=\"Límite municipal\"/>");
    zip2Lyr("../grijalva/data/anps.zip", anps, layer_ANPs);
    map.addLayer(layer_ANPs);
    layerControl.addOverlay(layer_ANPs, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(0,255,0,.3)\" stroke=\"rgba(128,152,72,1.0)\" stroke-dasharray=\"0.5,1\" stroke-dashoffset=\"0.5\"></rect></svg> Áreas Naturales Protegidas 2018");

    // Localize Leaflet.Draw texts
    L.drawLocal = {
        draw: {
            toolbar: {
                actions: {
                    title: "Cancelar dibujo",
                    text: "Cancelar"
                },
                finish: {
                    title: "Terminar dibujo",
                    text: "Terminar"
                },
                undo: {
                    title: "Eliminar último punto dibujado",
                    text: "Eliminar último punto"
                },
                buttons: {
                    polyline: "Dibujar una polilínea",
                    polygon: "Dibujar un polígono",
                    rectangle: "Dibujar un rectángulo",
                    circle: "Dibujar un círculo",
                    marker: "Dibujar un marcador",
                    circlemarker: "Dibujar un marcador circular"
                }
            },
            handlers: {
                circle: {
                    tooltip: {
                        start: "Haz click y arrastra para dibujar un círculo"
                    },
                    radius: "Radio"
                },
                circlemarker: {
                    tooltip: {
                        start: "Haz click en el mapa para ubicar el marcador circular"
                    }
                },
                marker: {
                    tooltip: {
                        start: "Haz click en el mapa para ubicar el marcador"
                    }
                },
                polygon: {
                    error: "<strong>Error:</strong>",
                    tooltip: {
                        start: "Haz click para empezar a dibujar la figura",
                        cont: "Haz click para continuar dibujando la figura",
                        end: "Haz click en el primer punto para cerrar la figura"
                    }
                },
                polyline: {
                    error: "<strong>Error:</strong> las líneas no deben cruzarse",
                    tooltip: {
                        start: "Haz click para empezar a dibujar la línea",
                        cont: "Haz click para continuar dibujando la línea",
                        end: "Haz click en el último punto para terminar la línea"
                    }
                },
                rectangle: {
                    tooltip: {
                        start: "Haz click y arrastra para dibujar un rectángulo"
                    }
                },
                simpleshape: {
                    tooltip: {
                        end: "Suelta el ratón para terminar de dibujar"
                    }
                }
            }
        },
        edit: {
            toolbar: {
                actions: {
                    save: {
                        title: "Guardar los cambios",
                        text: "Guardar"
                    },
                    cancel: {
                        title: "Cancelar la edición, descarta todos los cambios",
                        text: "Cancelar"
                    },
                    clearAll: {
                        title: "Limpiar todas las capas",
                        text: "Limpiar todo"
                    }
                },
                buttons: {
                    edit: "Editar capas",
                    editDisabled: "No hay capas que editar",
                    remove: "Eliminar capas",
                    removeDisabled: "No hay capas que eliminar"
                }
            },
            handlers: {
                edit: {
                    tooltip: {
                        text: "Arrastra el marcador para editar la figura",
                        subtext: "Haz click en cancelar para deshacer los cambios"
                    }
                },
                remove: {
                    tooltip: {
                        text: "Haz click en una figura para eliminarla"
                    }
                }
            }
        }
    }
    // leaflet draw control
    drawnItems = L.featureGroup().addTo(map);

    let drawControl = new L.Control.Draw({
        draw: {
            polygon: {
                showArea: true,
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            // disable toolbar item by setting it to false
            polyline: {
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            rectangle: {
                shapeOptions: {
                    color: "#42ffc3"
                }
            },
            marker: false,
            circlemarker: false,
            circle: false // Turns off this drawing tool
        },
        edit: {
            featureGroup: drawnItems
        }
    });
    map.addControl(drawControl);

    // set z-index of panes so actions can be done on drawnItems when editing/deleting
    map.on(L.Draw.Event.CREATED, event => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        let layer = event.layer,
            feature = layer.feature = layer.feature || {}; // Initialize feature

        feature.type = feature.type || "Feature"; // Initialize feature.type
        feature.properties = feature.properties || {}; // Initialize feature.properties

        drawnItems.addLayer(layer); // whatever you want to do with the created layer

        // give each drawn item an id and color from an array
        styleDrawnItems();
        // disable buttons if there are 10 drawn items
        toggleButtons();

        // after drawing shape, update chart with data for polygons contained inside it
        updateCharts();
    });

    map.on(L.Draw.Event.DELETESTART, () => {
        // before deleting shape, bring pane up
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
    });

    map.on(L.Draw.Event.DELETED, () => {
        // after deleting a drawn item, refresh the list of ids and colors
        styleDrawnItems();
        // enable buttons if there are less than 10 drawn items
        toggleButtons();

        // after deleting shape, send pane down
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // and update chart with data:
        // if there are drawnItems, use them. If not, use original data
        updateCharts();
    });

    map.on(L.Draw.Event.EDITSTART, () => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
        // before  editing shape, bring pane up
    });

    map.on(L.Draw.Event.EDITSTOP, () => {
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // before  editing shape, bring pane up
    });

    map.on(L.Draw.Event.EDITED, () => {
        // before  editing shape, send pane down
        $("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
        // after editing shape, update chart with data for polygons contained inside it
        updateCharts();
    });
}