/*
 * Copyright 2021 - All rights reserved.
 * Rodrigo Tapia-McClung
 *
 * January 2021
 */

/* global Promise, omnivore, JSZip, map, layerControl */
/* exported makeBaseMap */

let baseLayerPromises = [];

// 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";
}

let descargas, puentes, presas, cuencas, tuxtlaVH, zms, anps;

//  *** WMS INEGI ***
// 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"
});
//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
});
//  *** FIN WMS INEGI ***

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_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 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_presas", 409);
    createPane("pane_descargas", 410);
    createPane("pane_carreteras", 411);
    createPane("pane_puentes", 414);
    createPane("pane_wbnames",421);

    layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
    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");
    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");
    zip2Lyr("../grijalva/data/cuencas.zip", cuencas, 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");
}