{% load static %} {% include "django/forms/widgets/input.html" %}
 {% block extra_css %} {{block.super }}{% endblock %} {% block input %}

<div id="{{ map_id }}" style="height: 300px; width: 100%; z-index: 0"></div>
<input
    name="{{ widget.name }}"
    id="{{ widget.attrs.id }}"
    type="hidden"
    class="polygon-field"
    value="{{ widget.value|default:'' }}"
/>
<input
    name="{{ widget.name }}_geom"
    class="polygon-geom"
    type="hidden"
    value="{{ widget.value|default:'' }}"
/>
{% endblock %} {% block extra_js %} {{ block.super }}

<script>
    $(function () {
        $('input[id^="{{ widget.attrs.id }}"]').each(function (index) {
            if (index == 1) {
                var $input = $(this);
                var $map = $input.parent().find("#" + "{{ map_id }}");
                var $geom = $input.parent().find(".polygon-geom");
                var $polyfield = $input.parent().find(".polygon-field");

                // initialize map
                var map = L.map($map[0], {
                    center: [16.130262012034265, 30.019531249998607],
                    zoom: 4,
                    scrollWheelZoom: false,
                });

                // add basemap
                L.tileLayer(
                    "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                    {
                        attribution:
                            '&copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
                    }
                ).addTo(map);


                var style = {
                    color: '#3288ff',
                    opacity: 1.0,
                    fillOpacity: 0.3,
                    weight: 3,
                    clickable: false
                };
                L.Control.FileLayerLoad.LABEL = '<i class="fa-solid fa-file-arrow-up"></i>';
                var uploadControl = L.Control.fileLayerLoad({
                    fitBounds: true,
                    layerOptions: {
                        style: style,
                        pointToLayer: function (data, latlng) {
                            return L.circleMarker(
                                latlng,
                                { style: style }
                            );
                        }
                    }
                });
                // uploadControl.addTo(map);

                // initialize feature group of drawn items
                var drawnItems = new L.FeatureGroup();

                map.addLayer(drawnItems);



                // add draw control
                let drawControl;

                let canCreateNewDraw = true;


                function _initToolbar() {
                    if (drawControl) map.removeControl(drawControl);

                    drawControl = new L.Control.Draw({
                        edit: {
                            featureGroup: drawnItems,
                            edit: !canCreateNewDraw,
                            remove: !canCreateNewDraw,
                            poly: {
                                allowIntersection: true,
                            },
                            allowIntersection: true,
                        },
                        draw: {
                            polyline: false,
                            marker: false,
                            circle: false,
                            circlemarker: false,
                            rectangle: canCreateNewDraw,
                            polygon: canCreateNewDraw,
                        },
                    });

                    map.addControl(drawControl);
                    map.addControl(uploadControl);

                    if(canCreateNewDraw){
                        $input.parent().find(".leaflet-control-filelayer").show()

                    } else{
                        $input.parent().find(".leaflet-control-filelayer").hide()

                    }
                }

                var loadPolygon = function () {
                    var value = $input.val();

                    if (value) {

                        canCreateNewDraw = false;
                        

                        // Remove the SRID prefix
                        const wktWithoutSrid = value.replace(/^SRID=\d+;/, "");

                        // Extract the coordinates from the polygon string using a regex pattern
                        const match = /\((.*?)\)/.exec(wktWithoutSrid);

                        if (match) {
                            const coordinatePairs = match[1].split(", ");
                            const coordinates = coordinatePairs.map((pair) =>
                                pair.replace("(", "").split(" ").map(parseFloat)
                            );

                            revCoords = [];

                            coordinates.forEach((pol) => {
                                revCoords.push([pol[1], pol[0]]);
                            });

                            var polygon =
                                L.polygon(revCoords).addTo(drawnItems);
                            map.fitBounds(polygon.getBounds());
                        }
                    } 

                    _initToolbar();
                };

                map.on("draw:created", function (e) {
                    drawnItems.addLayer(e.layer);
                    canCreateNewDraw = false;
                    _initToolbar();

                    $polyfield.val(
                        JSON.stringify(e.layer.toGeoJSON().geometry)
                    );
                    $geom.val(JSON.stringify(e.layer.toGeoJSON()));
                });

                map.on("draw:edited", function (e) {
                    canCreateNewDraw = false;
                    _initToolbar();
                    e.layers.eachLayer(function (layer) {
                        var isIntersecting = false;

                        drawnItems.eachLayer(function (existingLayer) {
                            if (
                                layer !== existingLayer &&
                                layer.intersects(existingLayer)
                            ) {
                                drawnItems.removeLayer(layer);
                                isIntersecting = true;
                                return;
                            }
                        });

                        if (!isIntersecting) {
                            layer.setStyle({ color: "blue" });

                            $polyfield.val(
                                JSON.stringify(layer.toGeoJSON().geometry)
                            );
                            $geom.val(JSON.stringify(layer.toGeoJSON()));
                        }
                    });
                });

                map.on("draw:deleted", function (e) {
                    canCreateNewDraw = true;
                    _initToolbar();
                    $polyfield.val("");
                    $geom.val("");
                });

                loadPolygon();

                uploadControl.loader.on('data:loaded', function (e) {
                    var layer = e.layer;
                    if(e.layer.toGeoJSON().features){
                        console.log("Uploaded Layer",Object.values(e.layer._layers)[0]);

                        console.log("Uploaded Geojson",e.layer.toGeoJSON().features[0]);

                        if(e.layer.toGeoJSON().features[0].geometry.type === 'Polygon'){
                            drawnItems.addLayer(Object.values(e.layer._layers)[0]);
                            canCreateNewDraw = false;
                            _initToolbar();
        
                            $polyfield.val(
                                JSON.stringify(e.layer.toGeoJSON().features[0].geometry)
                            );
                            $geom.val(JSON.stringify(e.layer.toGeoJSON().features[0]));
                        }
                    }
                    
                    
                });


            }
        });
    });
</script>
{% endblock %}
