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

/* globals Promise */
/* exported layerControl */

let timeDimensionControl,
    map,
    overlay,
    glmap,
    osmLayer, cartoLightLayer, cartoDarkLayer,
    timeLayer,
    layerControl,
    tiles;

const getMinMax = table => {
    return new Promise(resolve => {
        //let table = "urbanization_year";
        const baseUrl = new URL(`/data`, window.location.href).href;
        let minmaxQuery = `${baseUrl}/query/${table}?columns=${`min(yeartrimes), max(yeartrimes)`}`;
        d3.json(minmaxQuery).then(minmax => {
            resolve(minmax[0]);
        });
    });
}

const setupMap = () => {
    return new Promise(resolve => {
        // make body tag to have style height: 100%
        $("body").css("height", "100%");
        osmLayer = L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
            maxZoom: 19,
            attribution: "&copy; <a href=\"http://osm.org/copyright\" target=\"_blank\">OpenStreetMap</a> contributors"
        });
        cartoLightLayer = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png", {
            maxZoom: 19,
            attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
        });
        cartoDarkLayer = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png", {
            maxZoom: 19,
            attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
        });

        //let bounds = cuencaBufferMask.getBounds();
        let southWest = L.latLng(19.87, -102.87),
            northEast = L.latLng(23.02, -99.31),
            bounds = L.latLngBounds(southWest, northEast);

        map = L.map("mexmap", {
            //center: [17.22, -92.28],
            minZoom: 8,
            zoom: 6,
            attributionControl: false,
            maxBounds: bounds
        }).setView([21.15, -100.94], 8);

        cartoDarkLayer.addTo(map);

        // set sync map on right
        let osmLayerOverlay = L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
                maxZoom: 19,
                attribution: "&copy; <a href=\"http://osm.org/copyright\" target=\"_blank\">OpenStreetMap</a> contributors"
            }),
            cartoLightLayerOverlay = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png", {
                maxZoom: 19,
                attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
            }),
            cartoDarkLayerOverlay = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png", {
                maxZoom: 19,
                attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
            });

        overlay = L.map("overlaydiv", {
            zoomControl: false,
            inertia: false,
            keyboard: false,
            //dragging: false,
            scrollWheelZoom: true,
            attributionControl: false,
            zoomAnimation: true
        }).setView([16.96, -92.97], 8);

        cartoDarkLayerOverlay.addTo(overlay);
        L.control.attribution({ position: "bottomright" }).addTo(overlay);

        // on base layer on main map, change base layer on overlay map
        map.on("baselayerchange", event => {
            overlay.eachLayer(l => overlay.removeLayer(l));
            if (event.name == "Carto Dark") {
                cartoDarkLayerOverlay.addTo(overlay);
            } else if (event.name == "Carto Light") {
                cartoLightLayerOverlay.addTo(overlay);
            } else if (event.name == "OpenStreetMap") {
                osmLayerOverlay.addTo(overlay);
            }
        });

        const offsetGlobal = (center, zoom, refMap, tgtMap) => {
            var refC = refMap.getContainer();
            var tgtC = tgtMap.getContainer();
            var pt = refMap.project(center, zoom)
                .subtract([refC.offsetLeft, refC.offsetTop])
                .subtract(refMap.getSize().divideBy(2))
                .add([tgtC.offsetLeft, tgtC.offsetTop])
                .add(tgtMap.getSize().divideBy(2));
            return refMap.unproject(pt, zoom);
        }

        map.sync(overlay, { offsetFn: offsetGlobal });

        resolve({ "map": map });
    });
}

const populateMap = async(mapData) => {

    let map = mapData.map;
    let munisLayer = L.geoJson(null, {
        style: {
            stroke: true,
            weight: 5,
            color: "grey",
            opacity: .35,
            fillOpacity: 0.05
        },
        interactive: false
    });
    let munis = omnivore.geojson("data/municipios.geojson", null, munisLayer);
    munis.addTo(map);

    let corredorLayer = L.geoJson(null, {
        style: {
            stroke: true,
            weight: 1,
            color: "#00ff00",
            opacity: 1,
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor:"rgba(0,240,2,0.05)"
        },
        interactive: false
    });
    let corredor = omnivore.geojson("data/corredor_bajio.geojson", null, corredorLayer);
    corredor.addTo(map);

    let bufferConLayer = L.geoJson(null, {
        style: {
            stroke: true,
            weight: 1,
            color: "#d5bef5",
            opacity: 1,
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(213,190,245,0.25)"
        },
        interactive: false
    });
    let bufferCon = omnivore.geojson("data/buffer_corredor_con_locs.geojson", null, bufferConLayer);
    bufferCon.addTo(map);

    let bufferSinLayer = L.geoJson(null, {
        style: {
            stroke: true,
            weight: 1,
            color: "#c43c39",
            opacity: 1,
            weight: 1.0,
            fill: true,
            fillOpacity: 1,
            fillColor: "rgba(196,60,57,0.25)"
        },
        interactive: false
    });
    let bufferSin = omnivore.geojson("data/buffer_corredor_sin_locs.geojson", null, bufferSinLayer);
    bufferSin.addTo(map);


    let baseLayers = {
        "Carto Dark": cartoDarkLayer,
        "Carto Light": cartoLightLayer,
        "OpenStreetMap": osmLayer
    };
    var overlays = {
        "<span id=\"bufferSin\"><svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(196,60,57,0.25)\" stroke=\"#c43c39\"></rect></svg>&nbsp; Interfaz periurbana del Corredor del Baj&iacute;o de<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2km <b>sin</b> localidades de m&aacute;s 10mil habitantes</span>": bufferSin,
        "<span id=\"bufferCon\"><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.25)\" stroke=\"#d5bef5\"></rect></svg>&nbsp; Interfaz periurbana del Corredor del Baj&iacute;o de<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2km <b>coin</b> localidades de m&aacute;s 10mil habitantes</span>": bufferCon,
        "<span id=\"corredor\"><svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(0,240,2,0.05)\" stroke=\"#00ff00\"></rect></svg>&nbsp; Corredor del Baj&iacute;o</span>": corredor,
        "<span id=\"munis\"><svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(128,128,128, 0.05)\" stroke=\"#808080\"></rect></svg>&nbsp; Contexto municipal</span>": munis,
    };

    layerControl = L.control.layers(baseLayers, overlays).addTo(map);
}

// hide initial screen and show map
$("#startHeader").remove();
$(".picker").remove();
$("#initial-backdrop").remove();
$("#mainContainer")[0].style.setProperty("display", "flex", "important");
let title = $("#title");
title.html(`<h2>Comportamiento periurbano en la regi&oacute;n metropolitana centro pa&iacute;s</h2>`);
$("#mexmap").show();

$("#odTableRow").removeClass("align-self-center");
$("#odCard").hide();

setupMap()
    .then(map => populateMap(map));