var map = L.map('map', { editable: true, zoomControl: false, drawControl: true }).setView([-4.125826277307029, 104.1881561279297], 10);

var pool = [];

var OpenStreetMap = document.getElementById("OpenStreetMap");
var WorldImagery = document.getElementById("WorldImagery");
var BingSatellite = document.getElementById("BingSatellite");
var GoogleSatellite = document.getElementById("GoogleSatellite");

var BING_KEY = 'Anj9XBZaRShAMdbXJlZ16iqEVpjikY1eY_dzqGl451WYkSKV3l_FJaFgMbhwdbLz'

loaderPage(false);

function loaderPage(stat) {
    if (stat == true) {
        $('.page_loader').show();
    } else {
        $('.page_loader').hide();
    }
};

$("#sidebar").hide()

maps = L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
    maxZoom: 22,
    minZoom: 4,
}).addTo(map);

OpenStreetMap.onclick = function() {
    maps = L.tileLayer("https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off", {
        maxZoom: 22,
        minZoom: 3,
    }).addTo(map);
};

WorldImagery.onclick = function() {
    // https://{s}.tiles.wmflabs.org/osm-no-labels/{z}/{x}/{y}.png
    maps = L.tileLayer("https://{s}.tiles.wmflabs.org/osm-no-labels/{z}/{x}/{y}.png", {
        maxZoom: 22,
        minZoom: 3,
    }).addTo(map);
};

BingSatellite.onclick = function() {

    maps = L.tileLayer.bing({ bingMapsKey: BING_KEY, maxNativeZoom: 22 }).addTo(map);
};

GoogleSatellite.onclick = function() {

    maps = L.tileLayer('http://mt0.google.com/vt/lyrs=y&hl=en&x={x}&y={y}&z={z}&s=Gal&apistyle=s.t:0|s.e:l|p.v:off', {
        maxZoom: 22,
        minZoom: 4,
    }).addTo(map);
};

$('#createPolygonTools').click(function() {
    polygonDrawer.enable();
});

var Marker = {};
var Poly = {};

var request = new XMLHttpRequest();
request.open("GET", "../static/batas.json", false);
request.send(null)
var batas = JSON.parse(request.responseText);
console.log(batas);


// map.on('click', function(e) {

// });


var geo_batas = L.geoJson(batas, {
    style: function(feature) {
        return {
            color: "#000000",
            weight: 1,
            opacity: 1,
            fillcolor: "#FFFFFF",
            fillOpacity: 0.1
        };
    },
    onEachFeature: function(feature, layer) {
        layer.on({
            click: function(e) {

            },
            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_batas.resetStyle(e.target);
            }

        });
    }
}).addTo(map);

map.on(L.Draw.Event.CREATED, function(e) {
    var layer = e.layer;

    $("#coordinateZone").empty();

    var type = e.layerType;
    var layer = e.layer;

    var shape = layer.toGeoJSON();
    let geoShape = shape.geometry.coordinates[0];

    let kordinat = "";
    for (j in geoShape) {

        kordinat += geoShape[j][0] + ' ' + geoShape[j][1];

        if (j <= (geoShape.length - 2)) {
            kordinat += ', ';
        }
    }

    window.thisBaseDrawPolygonLayer = layer;

    $("#coordinateZone").val(JSON.stringify(kordinat));
});

polygon_options = {
    showArea: false,
    shapeOptions: {
        stroke: true,
        color: '#6e83f0',
        weight: 4,
        opacity: 0.5,
        fill: true,
        fillColor: null, //same as color by default
        fillOpacity: 0.2,
        clickable: true
    }
}

var polygonDrawer = new L.Draw.Polygon(map, polygon_options);

polygonDrawer.on("click", function(event) {
    shapecoords.innerHTML = event.latlng.toString();
    map.fire("click", event); // Trigger a map click as well.

});

map.on('draw:created', function(e) {
    var type = e.layerType,
        layer = e.layer;

    // Do whatever you want with the layer.
    // e.type will be the type of layer that has been draw (polyline, marker, polygon, rectangle, circle)
    // E.g. add it to the map
    var lay = layer.addTo(map);
    Poly = lay;
    $("#PolygonModal").modal({
        backdrop: 'static',
        keyboard: false
    });
});

function cheakDFeas(e) {

    $('#latM').val();
    $('#lonM').val();

    $("#PointModal").modal();
    // Add marker to map at click location; add popup window
    var newMarker = new L.marker(e.latlng).addTo(map);
    Marker = newMarker;

    $('#latM').val(e.latlng.lat);
    $('#lonM').val(e.latlng.lng);

}

$('#createRadius').click(function() {
    map.on('click', cheakDFeas);
})

$("#closeP").click(function() {
    map.removeLayer(Poly);

});

$("#closeR").click(function() {
    map.removeLayer(Marker);
    map.off('click', cheakDFeas);
});

var results = L.layerGroup().addTo(map);

// listen for the results event and add every result to the map

$('#GetAddress').click(function() {
    $("#AddressModal").modal("show");
});

$("#id_provinsi ").change(function() {
    var prov_val = $(this).val();

    $.ajax({
        url: 'ajax/administrasi/',
        data: {
            'prov_val': prov_val
        },
        dataType: 'json',
        success: function(data) {
            var data_all_kab = []
            for (var i = 0; i < data['kab_res'].length; i++) {
                var data_k = data['kab_res'][i];
                var data_kab = `<option value="` +
                    data_k +
                    `">` +
                    data_k +
                    `</option>`;
                data_all_kab.push(data_kab)
            };
            $('#id_kab').html(`<option>Select Kabupaten</option>` + data_all_kab);

            $('#polypro').val(data['nama_pro']);

        }
    });
});

$("#id_kab").change(function() {
    var kab_val = $(this).val();
    var nama_pro = $('#polypro').val();
    loaderPage(true);

    $.ajax({
        url: 'ajax/kabupaten/',
        data: {
            'kab_val': kab_val,
            'prov_val': nama_pro
        },
        dataType: 'json',
        success: function(data) {
            loaderPage(false);
            var data_all_kab = []
            for (var i = 0; i < data['nama_kec'].length; i++) {
                var data_k = data['nama_kec'][i];
                var data_kab = `<option value="` +
                    data_k +
                    `">` +
                    data_k +
                    `</option>`;
                data_all_kab.push(data_kab)
            };
            $('#id_kec').html(`<option>Select Kecamatan</option>` + data_all_kab);

            $('#polykab').val(data['nama_kab']);
            $('#polypro').val(data['nama_pro']);

        }
    });
});

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

// var geo_build_gen = L.geoJson(null, {
//     style: function(feature) {
//         if (feature.properties.f4 == 'osm') {
//             return {
//                 color: "#00ff00",
//                 weight: 1,
//                 opacity: 2,
//                 zIndex: 1000
//             };

//         }
//         if (feature.properties.f4 == 'gen') {
//             return {
//                 color: "#ff0008",
//                 weight: 1,
//                 opacity: 2,
//                 zIndex: 1000
//             };
//         }
//         if (feature.properties.f4 == 'new') {
//             return {
//                 color: "#0400ed",
//                 weight: 1,
//                 opacity: 2,
//                 zIndex: 1000
//             };
//         }

//     },

//     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) {
//                     $('#id_poly').val(feature.properties.f1);
//                     $('#id_poly_delete').val(feature.properties.f1);
//                 }
//             });

//             $("#list-polygon tbody").append(`
//             <tr class="feature-row" id="` + L.stamp(layer) + `" lat="` + lattitud + `" lng="` + longitud + `">
//                 <td class="feature-name">
//                     ` + feature.properties.f2 + `
//                 </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_gen.resetStyle(e.target);
//             }
//         });
//         var content = `
//         <div class="tabbable">
//         <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
//             <li class="active text-primary" id="feature-title"><a href="#left-tab1-feas-upl" data-toggle="tab" id="info">Information</a></li>
//             <li><a href="#right-tab2-feas-upl" data-toggle="tab" id="edit">Edit Buildings</a></li>
//         </ul>

//         <div class="tab-content">

//             <div class="tab-pane active" id="left-tab1-feas-upl" style="padding-bottom: 17px;">
//                 <div style="width: 350px; margin-left:10px;">
//                     <table>
//                         <tr>
//                             <th>Id</th>
//                             <td>:&nbsp` + feature.properties.f1 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Name</th>
//                             <td>:&nbsp` + feature.properties.f2 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Information</th>
//                             <td>:&nbsp` + feature.properties.f3 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kelurahan</th>
//                             <td>:&nbsp` + feature.administrasi.f1 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kecamatan</th>
//                             <td>:&nbsp` + feature.administrasi.f2 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kab/Kota</th>
//                             <td>:&nbsp` + feature.administrasi.f3 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Provinsi</th>
//                             <td>:&nbsp` + feature.administrasi.f4 + `</td>
//                         </tr>

//                     </table>
//                 </div><br>
//                 <input id='delet-pol' class="btn btn-warning" type="submit" value="DELETE">

//             </div>
//             <div class="tab-pane" id="right-tab2-feas-upl" style="padding-bottom: 17px;">
//                 <div id="map-edit" style="width:500px;height: 250px;">
//                 </div><br>
//                 <input id='buttonsaveedit' class="btn btn-primary" type="submit" value="Save">
//             </div>
//             <input type="text" name="coordinateZoneedit" class="hidden" id="coordinateZoneedit" value="">
//             <input class="hidden" type="text" name='id-poly' id="id-poly" value="` + feature.properties.f1 + `">
//             <input class="hidden" type="text" name='sumber' id="sumber" value="gen">

//         </div>

//     </div>`;
//         layer.bindPopup(content);

//     }
// }).addTo(map);

// var geo_build_osm = L.geoJson(null, {
//     style: function(feature) {
//         if (feature.properties.f4 == 'osm') {
//             return {
//                 color: "#00ff00",
//                 weight: 1,
//                 opacity: 2,
//                 zIndex: 1000
//             };

//         }
//         if (feature.properties.f4 == 'gen') {
//             return {
//                 color: "#ff0008",
//                 weight: 1,
//                 opacity: 2,
//                 zIndex: 1000
//             };
//         }
//     },

//     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) {
//                     $('#id_poly').val(feature.properties.f1);
//                     $('#id_poly_delete').val(feature.properties.f1);
//                 }
//             });
//             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_osm.resetStyle(e.target);
//             }
//         });
//         var content = `<div class="tabbable">
//         <ul class="nav nav-tabs nav-tabs-bottom nav-justified">
//             <li class="active text-primary" id="feature-title"><a href="#left-tab1-feas-upl" data-toggle="tab" id="info">Information</a></li>
//             <li><a href="#right-tab2-feas-upl" data-toggle="tab" id="edit">Edit Buildings</a></li>
//         </ul>

//         <div class="tab-content">

//             <div class="tab-pane active" id="left-tab1-feas-upl" style="padding-bottom: 17px;">
//                 <div style="width: 350px; margin-left:10px;">
//                     <table>
//                         <tr>
//                             <th>Id</th>
//                             <td>:&nbsp` + feature.properties.f1 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Name</th>
//                             <td>:&nbsp` + feature.properties.f2 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Information</th>
//                             <td>:&nbsp` + feature.properties.f3 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kelurahan</th>
//                             <td>:&nbsp` + feature.administrasi.f1 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kecamatan</th>
//                             <td>:&nbsp` + feature.administrasi.f2 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Kab/Kota</th>
//                             <td>:&nbsp` + feature.administrasi.f3 + `</td>
//                         </tr>
//                         <tr>
//                             <th>Provinsi</th>
//                             <td>:&nbsp` + feature.administrasi.f4 + `</td>
//                         </tr>

//                     </table>
//                 </div><br>
//                 <input id='delet-pol' class="btn btn-warning" type="submit" value="DELETE">
//             </div>
//             <div class="tab-pane" id="right-tab2-feas-upl" style="padding-bottom: 17px;">
//                 <div id="map-edit" style="width:500px;height: 250px;">
//                 </div><br>
//                 <input id='buttonsaveedit' class="btn btn-primary" type="submit" value="Save">
//             </div>
//             <input type="text" name="coordinateZoneedit" class="hidden" id="coordinateZoneedit" value="">
//             <input class="hidden" type="text" name='id-poly' id="id-poly" value="` + feature.properties.f1 + `">
//             <input class="hidden" type="text" name='sumber' id="sumber" value="osm">

//         </div>

//     </div>`;
//         layer.bindPopup(content);
//     }
// }).addTo(map);

// $("#edit").click(function() {
//     alert("cel")

// });

jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

// map.on('contextmenu', function(e) {
//     $("#map-create").remove();

//     // document.getElementsByClassName('leaflet-popup-content').style.width = "550px";
//     var popup = L.popup()
//         .setLatLng(e.latlng)
//         .setContent(`
//         <div id="map-create" style="height: 250px;">
//         <input type="button" id="create" value="Create" style="z-index: 1000;position:relative;">
//         </div>
//         <br>

//         <label class="control-label col-lg-2 label-12">Name</label>
//         <input type="text" class="form-control" name="name_create" id="name_create" value=""><br>
//         <label class="control-label col-lg-2 label-12">Information</label>
//         <input type="text" class="form-control" name="info_create" id="info_create" value=""><br>
//         <div class="row">
//         <div class="col-md-2">

//         </div>
//         <div class="col-md-7">
//         </div>
//         <div class="col-md-3">
//             <input type="button" class="btn btn-primary" id="create_save" value="SAVE" style="margin-right:30px;">
//         </div>
//         </div>
//         <input type="text" name="poly_create" class="hidden" id="poly_create" value="">
//         `)
//         .openOn(map);

//     map.openPopup(popup);

//     var map_create = L.map('map-create', {
//         editable: true,
//         zoomControl: false,
//         drawControl: true
//     }).setView([e.latlng.lat, e.latlng.lng], 20.5);

//     map_created = L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
//         maxZoom: 22,
//         minZoom: 4,
//     }).addTo(map_create);

//     map_create.invalidateSize();

//     $('#create').click(function() {

//         polygonDraweredit.enable();
//     });

//     var Marker = {};
//     var Poly = {};

//     map_create.on(L.Draw.Event.CREATED, function(e) {
//         var layer = e.layer;

//         $("#poly_create").empty();

//         var type = e.layerType;
//         var layer = e.layer;

//         var shape = layer.toGeoJSON();
//         let geoShape = shape.geometry.coordinates[0];

//         let kordinat = "";
//         for (j in geoShape) {

//             kordinat += geoShape[j][0] + ' ' + geoShape[j][1];

//             if (j <= (geoShape.length - 2)) {
//                 kordinat += ', ';
//             }
//         }

//         window.thisBaseDrawPolygonLayer = layer;

//         $("#poly_create").val(JSON.stringify(kordinat));
//     });

//     polygon_options = {
//         showArea: false,
//         shapeOptions: {
//             stroke: true,
//             color: '#6e83f0',
//             weight: 1.5,
//             opacity: 2,
//             fill: true,
//             fillColor: null, //same as color by default
//             fillOpacity: 0.3,
//             clickable: true
//         }
//     }

//     var polygonDraweredit = new L.Draw.Polygon(map_create, polygon_options);

//     polygonDraweredit.on("click", function(event) {
//         shapecoords.innerHTML = event.latlng.toString();
//         map_create.fire("click", event); // Trigger a map click as well.
//     });

//     map_create.on('draw:created', function(e) {
//         var type = e.layerType,
//             layer = e.layer;

//         var lay = layer.addTo(map_create);
//         Poly = lay;
//     });

// });


// $(document).on("click", "#create_save", function(e) {
//     var polygin = $('#poly_create').val();
//     var name_poly = $('#name_create').val();
//     var info_poly = $('#info_create').val();
//     loaderPage(true);

//     $.ajax({
//         url: "api/v1/create/",
//         data: {
//             'polygon': polygin,
//             'name': name_poly,
//             'info': info_poly
//         },
//         dataType: 'json',

//         success: function(data) {
//             map.closePopup();
//             loaderPage(false);
//         }
//     });
// });

$(document).on("click", "#info", function() {
    document.getElementsByClassName('leaflet-popup-content')[0].style.width = "301px";
    document.getElementsByClassName('leaflet-popup')[0].style.left = "-171px";
});


var geo_jln = L.geoJson(null, {
    style: function(feature) {
        return {
            color: "#fcba03",
            weight: 5,
            opacity: 2,
            fillcolor: "#fcba03",
            fillOpacity: 0
        };
    },
    onEachFeature: function(feature, layer) {
        layer.on({
            mouseover: function(e) {
                var layer = e.target;
                layer.setStyle({
                    weight: 5,
                    Color: "#067800",
                    fillColor: "#067800",

                });
                if (!L.Browser.ie && !L.Browser.opera) {
                    layer.bringToFront();
                }

            },
            mouseout: function(e) {
                geo_jln.resetStyle(e.target);
            }

        });
        var popupContent = feature.properties.f2;
        layer.bindTooltip(popupContent);
        layer.bindPopup(popupContent);
    }
}).addTo(map);

function geo_json_jln(data) {
    geo_jln.addData(data)
}

function geo_json_build_osm(data) {
    geo_build_osm.addData(data)
}

function geo_json_build_gen(data) {
    geo_build_gen.addData(data)
}


$("#id_kec").change(function() {
    var kec_val = $(this).val();
    var kab_val = $('#polykab').val();
    var pro_val = $('#polypro').val();
    loaderPage(true);
    $.ajax({
        url: 'ajax/kecamatan/',
        data: {
            'kec_val': kec_val,
            'kab_val': kab_val,
            'pro_val': pro_val
        },
        dataType: 'json',
        success: function(data) {
            loaderPage(false);
            var data_all_kab = []
            for (var i = 0; i < data['nama_desa'].length; i++) {
                var data_k = data['nama_desa'][i];
                var data_kab = `<option value="` +
                    data_k +
                    `">` +
                    data_k +
                    `</option>`;
                data_all_kab.push(data_kab)
            };
            $('#id_desa').html(`<option>Select Desa/Kelurahan</option>` + data_all_kab);

            $('#polykab').val(data['nama_kab']);
            $('#polypro').val(data['nama_pro']);
            $('#polykec').val(data['nama_kec']);

        }
    });
});

$(document).on('click', 'li', function() {
    $('#provinsi').val($(this).text());
    $('#provinsiList').fadeOut();
});