/* global Bdf,Geo,L */

Geo.Fiches = {};

Geo.Fiches.ARGS = {
    mapIp: "",
    geojsonUrl: ""
};

Geo.Fiches.loadGeoJson = function (map, url) {
    $.ajax({
        url: url,
        dataType: "json",
        success: function (data, textStatus) {
            _convertGeoJson(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown)  {
            Bdf.log(textStatus);
        }
    });
    
    
    function _convertGeoJson(data) {
        let markers = new L.MarkerClusterGroup();
        let geoJsonLayer = L.geoJson(data, {
        onEachFeature: function (feature, layer) {
            let title = feature.properties.phrase + " – " + feature.properties.title;
            layer.bindTooltip(title);
            layer.bindPopup(Bdf.render("geo:popup", {
                title: title,
                id: feature.properties.id,
                corpus: feature.properties.corpus,
                editable: feature.properties.editable
            })); 
        }
        });
        markers.addLayer(geoJsonLayer);
        map.addLayer(markers);
        let bounds = markers.getBounds();
        let zoom = map.getBoundsZoom(bounds);
        let currentZoom = map.getZoom();
        if ((zoom > currentZoom) && (zoom > 15)) {
            zoom = 15;
        }
        map.setView(bounds.getCenter(), zoom);
    }
    
};


$(function () {
    Bdf.initTemplates();
    var args = Geo.Fiches.ARGS;
    var map = Geo.init(args.mapId, 10, 0, 2);
    Geo.Fiches.loadGeoJson(map, args.geojsonUrl);
});
