{{define "map"}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add a default marker</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script src='https://api.mapbox.com/mapbox-gl-js/v2.11.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.11.0/mapbox-gl.css' rel='stylesheet' />
<script src=https://cdnjs.cloudflare.com/ajax/libs/mapbox-polyline/1.1.1/polyline.js></script>

<script src='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js'></script>
<link href='https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css' rel='stylesheet' />


</head>
<body>
	
	<input id="de" type="hidden" value="{{.ViewState.group.Data.depart.geometry.coordinates}}">
	<input id="ar" type="hidden" value="{{.ViewState.group.Data.arrive.geometry.coordinates}}">
	<input id="des" type="hidden" value="{{.ViewState.group.Data.depart.geometry.coordinates}}">
	<input id="arri" type="hidden" value="{{.ViewState.group.Data.arrive.geometry.coordinates}}">
    {{range .ViewState.beneficiaries}}                   
    {{if (index $.ViewState.groups .ID) }}
    <input id="passager"  type="hidden"value="{{(index $.ViewState.groups .ID).Data.depart.geometry.coordinates}}">
    {{end}}
    {{end}}

<div>
        <span id="polyline-info-content"></span>
        <div id='map' style='width: 730px; height: 300px;'></div>
        <script>

        function routeNotOptimized(body) {
            $.ajax({
                url: 'https://routing.geo.scity.coop/route?json=' + JSON.stringify(body),
                type: "GET",
                success : retrievePolylineInfo,
                error: errorRoute,
            });
        }

function errorRoute() {
    console.log("errorRoute : couldn't find a route")
}

            function reverseCoord(geojsonCoord){
    if(geojsonCoord != null) {
        var tmpGeojsonCoord =[];
        for (var i=0; i<geojsonCoord.length; i++) {
            tmpGeojsonCoord.push([geojsonCoord[i][1],geojsonCoord[i][0]]);
        }
        return tmpGeojsonCoord;
    }
}

 function drawPolylineOnMap(polylineCoord) {
    var memberSource;

    var mapLayer = map.getLayer('route');
    var memberSource = map.getSource('route');
    if(typeof mapLayer !== 'undefined') {
        map.removeLayer('route')
        map.removeSource('route')
    }
        map.addLayer({
            'id': 'route',
            'type': 'line',
            'source': {
                "type": "geojson",
                "data": {
                    "type": "Feature",
                    "geometry": {
                        "type": "LineString",
                        "coordinates": reverseCoord(polylineCoord)
                    },
                }
            },
            'layout': {
                'line-join': 'round',
                'line-cap': 'round'
            },
            'paint': {
            'line-color': '#03A9F4',
                'line-width': 7
            }
        });
        var i = document.getElementById('de').value
		var words = i.split(' ');
		 const w = words[0].split('[')
		 const ww = words[1].split(']')
		 a = (w[1]);
		 b = (ww[0])
         depCoord = [a, b]
         var ar = document.getElementById('ar').value
		var wordsr = ar.split(' ');
		 const wr = wordsr[0].split('[')
		 const wwr = wordsr[1].split(']')
		 var r = (wr[1]);
		 var br = (wwr[0])
         destCoord = [r, br]
        map.setZoom(9);
       
        map.fitBounds([[depCoord[0],depCoord[1]],[destCoord[0],destCoord[1]]],{padding: 40});   
}

    function retrievePolylineInfo(polylineInfo) {
        var polylineString = ""
        for (var i=0; i < polylineInfo.trip.legs.length ; i++){
            polylineString = polylineString + polylineInfo.trip.legs[i].shape
        }
        var polylineCoord = polyline.decode(polylineString, 6)
        var rideDuration =  polylineInfo.trip.summary.time
        var rideDistance = polylineInfo.trip.summary.length
        if (rideDuration != null && rideDistance != null) {
            document.getElementById("polyline-info-content").innerHTML = "Durée : " + (Math.round(((rideDuration / 60) + Number.EPSILON) * 100) / 100) + " min<br/>Distance : " + rideDistance + " km";
        }
       
        // console.log("rideDuration :", rideDuration, ", rideDistance ",rideDistance)
        if(polylineCoord != null && polylineCoord.length > 0 ){
        
            drawPolylineOnMap(polylineCoord)
        }
}

function createPolyline() {
    origin= [a, b]

    destination = [r, br]


    if(origin != null && destination != null && origin != "" && destination != ""){
       
        var hash_locs = [];
        hash_locs.push({
            'lat' : (origin[1]),
            'lon' : (origin[0])
          })
          hash_locs.push({
            'lat' : (destination[1]),
            'lon' : (destination[0])
          })
        var body = {"locations":[{
            'lat' : (origin[1]),
            'lon' : (origin[0])
          },{
            'lat' : (destination[1]),
            'lon' : (destination[0])
          }],"costing":"auto"}
        $.ajax({
            url: 'https://routing.geo.scity.coop/route?json=' + JSON.stringify(body),
            type: "GET",
            success : retrievePolylineInfo,
            error: routeNotOptimized(body),
        });
      
    }
}
            var depCoord = []
            var destCoord = []
            var other = []
            var a, b
            depCoord = [a, b]
           
        const map = new maplibregl.Map({
            container: 'map', 
            style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL', 
            center: [-74.5, 40],
            zoom: 9, 
        });
        map.addControl(new maplibregl.NavigationControl(), 'bottom-right');
        var markers = []
        var pass = []

        //////////////////Code to add position in the map///////////////
        var ii = document.querySelectorAll("#passager")
        for (var i = 0; i < ii.length; i++){
            var v = ii[i].value
            var val = ii[i].value.split(' ')
            const wl = val[0].split('[')
            const wwl = val[1].split(']')
            al = (wl[1]);
            bl = (wwl[0])
            other = [al, bl]
            {var marker = new maplibregl.Marker()
            .setLngLat([al, bl])//position of passager
            .addTo(map);
            pass.push(marker)}
        }

		 var i = document.getElementById('de').value
		var words = i.split(' ');
		 const w = words[0].split('[')
		 const ww = words[1].split(']')
		 a = (w[1]);
		 b = (ww[0])
         depCoord = [a, b]
		//arrive
		var ar = document.getElementById('ar').value
		var wordsr = ar.split(' ');
		 const wr = wordsr[0].split('[')
		 const wwr = wordsr[1].split(']')
		 var r = (wr[1]);
		 var br = (wwr[0])
         destCoord = [r, br]
		
		 /////
		{var marker = new maplibregl.Marker();
		marker.setLngLat([a, b])//starting position
		departureMarker = marker.addTo(map);
		
		map.flyTo({
        center: [a, b]
       
    });
   
    markers.push(marker)
  createPolyline()
}
   
	{var marker = new maplibregl.Marker();
	marker.setLngLat([r, br])//ending position
		destinationMarker = marker.addTo(map);
		createPolyline()
		}
    markers.push(marker)
    
        </script>
</body>
</html>
{{end}}