<!DOCTYPE html>
<html style="height:100%;margin:0;padding:0;">
<head>
  <title>Tests edit line - polygon</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
  <script src="./leaflet/leaflet-hash.js"></script>
  <style type="text/css">
    .leaflet-tile-container { pointer-events: auto; }
  </style>
</head>
  <body style="height:100%;margin:0;padding:0;">
    <div id="map" style="height:100%"></div>
    <script>
    const map = L.map('map').setView([50.5, 5.57], 10);

    const cyclosm = L.tileLayer('https://{s}.tiles.champs-libres.be/cyclosm/{z}/{x}/{y}.png', {
        subdomains: "abc",
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 20
    });
    
    map.addLayer(cyclosm);

    const hash = L.hash(map);

    let geometryType = 'POLYGON'; //'POINT' | 'LINESTRING' | 'POLYGON'
    let myMarker = null;
    let polyline = null;
    let previousPolyline = null;
    let previousLayerPoint = null;

    let polygon = null;
    let firstPolygonPoint = null;

    const lineDraw = L.polyline([], {color: '#11aa9e', dashArray: '6', lineCap: 'butt'}).addTo(map);

    const pointDistance = (pointA, pointB) => {
        const SNAP_DISTANCE = 6;
        let distancePixel = Math.sqrt(Math.abs((pointB.x - pointA.x)**2 - (pointB.y - pointA.y)**2));
        return distancePixel < SNAP_DISTANCE;
    };

    const arePointsSnapped = (previousPoint, currentPoint) => 
        (previousPoint && currentPoint) ? pointDistance(previousPoint, currentPoint) : false;

    switch(geometryType){
        case 'LINESTRING':
            map.on('mousemove', (e) => {
                if(polyline){
                    let lastDrawPoint = polyline.getLatLngs()[polyline.getLatLngs().length - 1];
                    lineDraw.setLatLngs([lastDrawPoint, e.latlng]);
                }
            });
            break;
        case 'POLYGON':
            map.on('mousemove', (e) => {
                if(polygon){
                    let lastDrawPoint = polygon.getLatLngs()[0][polygon.getLatLngs()[0].length - 1];
                    let firstDrawPoint = polygon.getLatLngs()[0][0];
                    lineDraw.setLatLngs([firstDrawPoint, e.latlng, lastDrawPoint]);
                }
            });
            break;
    }

    map.on('click', (e) => {
        console.log(e);
        
        switch(geometryType){
            case 'POINT':
            default:
                if (myMarker !== null) {
                    map.removeLayer(myMarker);
                }
                myMarker = L.marker(e.latlng).addTo(map);
                break;
            case 'LINESTRING':
                lineDraw.setLatLngs([]);
                if (polyline === null){
                    console.log(previousPolyline)
                    if (previousPolyline !== null){
                        map.removeLayer(previousPolyline);
                    }
                    polyline = L.polyline([e.latlng], {color: '#11aa9e'}).addTo(map);
                } else {
                    if (arePointsSnapped(previousLayerPoint, e.layerPoint)) {
                        console.log('reset line')
                        previousPolyline = polyline;
                        polyline.setStyle({color: '#60b15c'});
                        polyline = null;                       
                    } else {
                        polyline.addLatLng(e.latlng);
                        previousLayerPoint = e.layerPoint;
                    }
                }
                break;
            case 'POLYGON':
                lineDraw.setLatLngs([]);
                if (polygon === null){
                    polygon = L.polygon([e.latlng], {color: '#11aa9e'}).addTo(map);
                    firstPolygonPoint = e.layerPoint;
                } else {
                    if (arePointsSnapped(firstPolygonPoint, e.layerPoint)) {
                        console.log('close the polygon')
                        polygon.setStyle({color: '#60b15c'});
                        polygon = null;
                    } else {
                        polygon.addLatLng(e.latlng);
                    }
                }
                break;

        }

    });

    </script>
  </body>
</html>