var map = L.map('map', { editable: true, zoomControl: false, drawControl: true }).setView([-2, 118], 5);

// var OpenStreetMap = document.getElementById("OpenStreetMap");
// var WorldImagery = document.getElementById("WorldImagery");
// var WorldTopoMap = document.getElementById("WorldTopoMap");
// var WorldTerrainBase = document.getElementById("WorldTerrainBase");
// var WorldShadedRelief = document.getElementById("WorldShadedRelief");
// var WorldPhysicalMap = document.getElementById("WorldPhysicalMap");
// var NatGeoWorldMap = document.getElementById("NatGeoWorldMap");
// var WorldLightGrayBase = document.getElementById("WorldLightGrayBase");
// var MapboxSatellite = document.getElementById("MapboxSatellite");
// var MapboxStreet = document.getElementById("MapboxStreet");
// var MapboxGray = document.getElementById("MapboxGrayscale");

var BING_KEY = 'Anj9XBZaRShAMdbXJlZ16iqEVpjikY1eY_dzqGl451WYkSKV3l_FJaFgMbhwdbLz'

var tile_bing = L.tileLayer.bing({ bingMapsKey: BING_KEY, maxNativeZoom: 22 }
    // BING_KEY, {
    // 'minZoom': 4,
    // 'maxZoom': 22
    // }
).addTo(map);

var tile_OSM = L.tileLayer(
    "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        "attribution": "Data by \u0026copy; \u003ca href=\"http://openstreetmap.org\"\u003eOpenStreetMap\u003c/a\u003e, under \u003ca href=\"http://www.openstreetmap.org/copyright\"\u003eODbL\u003c/a\u003e.",
        "detectRetina": false,
        "maxNativeZoom": 18,
        "maxZoom": 22,
        "minZoom": 3,
        "noWrap": false,
        "opacity": 1,
        "subdomains": "abc",
        "tms": false
    }
).addTo(map);

var tile_World_Imagery = L.tileLayer(
    "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", {
        "attribution": "Esri",
        "detectRetina": false,
        "maxNativeZoom": 18,
        "maxZoom": 22,
        "minZoom": 4,
        "noWrap": false,
        "opacity": 1,
        "subdomains": "abc",
        "tms": false
    }
).addTo(map);

var tile_google = L.tileLayer(
    "http://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}", {
        "attribution": "Data by \u0026copy; \u003ca href=\"http://openstreetmap.org\"\u003eOpenStreetMap\u003c/a\u003e, under \u003ca href=\"http://www.openstreetmap.org/copyright\"\u003eODbL\u003c/a\u003e.",
        "detectRetina": false,
        "maxNativeZoom": 18,
        "maxZoom": 22,
        "minZoom": 3,
        "noWrap": false,
        "opacity": 1,
        "subdomains": "abc",
        "tms": false
    }
);

var pool = [];
var Marker = {};

var polbang = '{{ polbang }}'.replace(/&#x27;/g, '"');
var polibag = JSON.parse("" + polbang + "");

function get_avg(pointt) {
    var sum = 0;
    for (var i = 0; i < pointt.length; i++) {
        sum += parseInt(pointt[i], 10);
    }
    return sum / pointt.length;
}

var lattitud, longitud;

if (polibag[0].geometry.type == 'MultiPolygon') {
    var lat_tot = 0;
    for (var i = 0; i < polibag[0].geometry.coordinates[0][0].length; i++) {
        lat_tot += parseInt(polibag[0].geometry.coordinates[0][0][i][1]);
    }
    var lng_tot = 0;
    for (var i = 0; i < polibag[0].geometry.coordinates[0][0].length; i++) {
        lng_tot += parseInt(polibag[0].geometry.coordinates[0][0][i][0]);
    }

    lattitud = polibag[0].geometry.coordinates[0][0][0][1];
    longitud = polibag[0].geometry.coordinates[0][0][0][0];
} else {
    var lat_tot = 0;
    for (var i = 0; i < polibag[0].geometry.coordinates[0].length; i++) {
        lat_tot += parseInt(polibag[0].geometry.coordinates[0][i][1]);
    }
    var lng_tot = 0;
    for (var i = 0; i < polibag[0].geometry.coordinates[0].length; i++) {
        lng_tot += parseInt(polibag[0].geometry.coordinates[0][i][0]);
    }

    lattitud = polibag[0].geometry.coordinates[0][0][1];
    longitud = polibag[0].geometry.coordinates[0][0][0];
};


$(document).ready(function() {
    map.setView([lattitud, longitud], 17);

});

$(document).on("click", ".feature-row", function(e) {

    $(document).off("mouseout", ".feature-row", clearHighlight);
    sidebarClick($(this).attr("lat"), $(this).attr("lng"));
    if (Marker != undefined) {
        map.removeLayer(Marker);
    };
    Marker = L.marker([$(this).attr("lat"), $(this).attr("lng")]).addTo(map);
});

function sidebarClick(lt, lg) {
    map.setView([lt, lg], 18);

    if (document.body.clientWidth <= 767) {
        $("#sidebar").hide();
        map.invalidateSize();
    }
}

var geocodeService = L.esri.Geocoding.geocodeService();
var geocoderNominatim = new L.Control.Geocoder.Nominatim();

var geo_build = L.geoJson(null, {
    style: function(feature) {
        return {
            color: "#00ff00",
            weight: 1,
            opacity: 2
        };
    },

    onEachFeature: function(feature, layer) {
        if (feature.properties) {

            var lattitud, longitud;
            if (feature.geometry.type == 'MultiPolygon') {
                lattitud = feature.geometry.coordinates[0][0][0][1];
                longitud = feature.geometry.coordinates[0][0][0][0];

            } else {
                lattitud = feature.geometry.coordinates[0][0][1];
                longitud = feature.geometry.coordinates[0][0][0];
            };

            layer.on({
                click: function(e) {
                    var geogeo = geocodeService.reverse().latlng(e.latlng).run(function(error, result) {
                        var content = `
                        <table class="table table-striped table-bordered table-condensed">
                            <tr>
                                <th>Id</th>
                                <td>` + feature.properties.f1 + `</td>
                            </tr>
                            <tr>
                                <th>Name</th>
                                <td>` + feature.properties.f2 + `</td>
                            </tr>
                            <tr>
                                <th>Information</th>
                                <td>` + feature.properties.f3 + `</td>
                            </tr>
                            <tr>
                                <th>Address</th>
                                <td>` + result.address.Address + `, ` + result.address.District + `, ` + result.address.Subregion + `</td>
                            </tr>
                            <tr>
                                <th>Zip Code</th>
                                <td>` + result.address.Postal + `</td>
                            </tr>
                        <table>`;
                        // console.log(result)

                        $("#feature-info").html(content);
                        if (error) {
                            return;
                        }
                    });

                    $("#feature-title").html(feature.properties.f1);
                    $("#featureModal").modal("show");
                    $("#button-ijo").html(`
                    <a class='btn btn-danger' href="delete/` + feature.properties.f1 + `/` + '{{ user.username }}' + `" onclick="return confirm('Pastikan anda yakin menghapus polygon ini');">Delete</a>
                    <a class='btn btn-warning' href="update/` + feature.properties.f1 + `/` + '{{ user.username }}' + `">Edit</a>
                    `);
                }
            });

            $("#feature-list tbody").append(`
            <tr class="feature-row" id="` + L.stamp(layer) + `" lat="` + lattitud + `" lng="` + longitud + `">
                <td style="vertical-align: middle;"></td><td class="feature-name">
                    ` + feature.properties.f2 + `
                </td>
                <td style="vertical-align: middle;">
                    <i class="fa fa-chevron-right pull-right"></i>
                </td>
            </tr>`);
            pool.push({
                name: feature.properties.f2,
                id: L.stamp(layer),
                lat: lattitud,
                lng: longitud
            });

        }
        layer.on({
            mouseover: function(e) {
                var layer = e.target;
                layer.setStyle({
                    weight: 1,
                    Color: "#067800",
                    fillColor: "#067800",

                });
                if (!L.Browser.ie && !L.Browser.opera) {
                    layer.bringToFront();
                }
            },
            mouseout: function(e) {
                geo_build.resetStyle(e.target);
            }
        });
    }
}).addTo(map);

function geo_json_build(data) {
    geo_build.addData(data);
}

let list_poly = [];
for (var i = 0; i < polibag.length; i++) {
    geoj = polibag[i];
    list_poly.push(geoj);
};
geo_json_build(list_poly);

var layer_control_b74c5cd0a2554891a4e8bd30ef19cc62 = {
    base_layers: {
        "bing satellite": tile_bing,
        "Esri Satellite": tile_World_Imagery,
        "google": tile_google,
        "openstreetmap": tile_OSM
    },
    overlays: {
        "Buildings": geo_build,
    },
};

L.control.layers(
    layer_control_b74c5cd0a2554891a4e8bd30ef19cc62.base_layers,
    layer_control_b74c5cd0a2554891a4e8bd30ef19cc62.overlays, {
        "autoZIndex": true,
        "collapsed": true,
        "position": "bottomright"
    }
).addTo(map);