<!--
Coded by Leonard Selvaraja (c) 2020 
Package: iCrew v4.3 Premium

Packages used: 
Leaflet Icon Pulse.js
Leaflet Hotline.js 
Leaflet Cluster.js
-->

<div class="mapcenter" align="center">
   <div id="route_map" style="width: 80%; height: 500px"></div>
</div>

<style>
   .leaflet-pulsing-icon {
   border-radius: 100%;
   box-shadow: 1px 1px 8px 0 rgba(0,0,0,0.75);
   }
   .leaflet-pulsing-icon:after {
   content: "";
   border-radius: 100%;
   height: 300%;
   width: 300%;
   position: absolute;
   margin: -100% 0 0 -100%;
   }
   @keyframes pulsate {
   0% {
   transform: scale(0.1, 0.1);
   opacity: 0;
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   }
   50% {
   opacity: 1;
   -ms-filter: none;
   filter: none;
   }
   100% {
   transform: scale(1.2, 1.2);
   opacity: 0;
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   }
   }
</style>
<script src="<?php echo SITE_URL?>/lib/js/base_map.js"></script>
<script src="https://rawgit.com/mapshakers/leaflet-icon-pulse/master/src/L.Icon.Pulse.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet.markercluster@1.0.6/dist/leaflet.markercluster.js"></script>
<script src="https://iosphere.github.io/Leaflet.hotline/dist/leaflet.hotline.js"></script>
<script type="text/javascript">
   // Creating a new map element.
   const map = createMap({
   	render_elem: 'route_map',
   	provider: '<?php echo Config::Get("MAP_TYPE"); ?>',
   });
   
   	function get_api_request(yourUrl){
   		var Httpreq = new XMLHttpRequest(); 
   		Httpreq.open("GET",yourUrl,false);
   		Httpreq.send(null);
   		return Httpreq.responseText;          
   	}
   		
   	 var legend = L.control({position: 'bottomright'});
   legend.onAdd = function (map) {
   
      var div = L.DomUtil.create('div', 'info legend');
          div.innerHTML = '<img src="<?php echo SITE_URL; ?>/iCrew/favicon.png" style="width: 50px; height: auto;" />';
      return div;
   };
   legend.addTo(map);
   
    // Flight Map Altitudes            	
	var hotlineOptions = {
		min: 0,
		max: 41000,
		palette: {
			0.1: '#f2ff00',
			0.3: '#73ff00',
			0.5: '#00ff80',
			0.7: '#00d5ff', 
			0.8: '#0004ff',
			1.0: '#7b00ff',
        },
        weight: 3,
        outlineColor: '#000000',
        outlineWidth: 1,
	};


   //Initializing Cluster Group
   var markersLayer = new L.LayerGroup(); 
   var markers = L.markerClusterGroup();
   map.addLayer(markersLayer);
   
   	var apiURL = "<?php echo SITE_URL; ?>/action.php/pireps/pirep_details_api/<?php echo $pirepid; ?>";
   	var pirep = JSON.parse(get_api_request(apiURL));
   	
   	var departure = JSON.parse(get_api_request("<?php echo SITE_URL; ?>/action.php/pireps/airportdata_api/" + pirep.depicao));
   	var marker = L.marker([departure.lat, departure.lng]).bindTooltip(departure.icao +" "+ departure.name).addTo(map);
   	
   	var arrival = JSON.parse(get_api_request("<?php echo SITE_URL; ?>/action.php/pireps/airportdata_api/" + pirep.arricao));
   	var marker = L.marker([arrival.lat, arrival.lng]).bindTooltip(arrival.icao +" "+ arrival.name).addTo(map);
   	
   	
   var depCoords = new L.LatLng(departure.lat, departure.lng);
   var arrCoords = new L.LatLng(arrival.lat, arrival.lng);
   
   
   let points = []; // For Waypoints when there is no "RawData"
   let hotline = []; // For Waypoints when there is "RawData"
   var speed = []; // For the graph
   var altitude = []; // For the graph
   var time = []; // For the graph
   
   
   
   points.push(depCoords);
           
   
   // rendering for if there's smartcars data
   if(pirep.rawdata instanceof Object && pirep.rawdata.points !== undefined && Array.isArray(pirep.rawdata.points)) {
   	$.each(pirep.rawdata.points, function(i, nav) {
   	if(nav.lat == 0 || nav.lng == 0 || nav.lat === undefined || nav.lng === undefined) {
   		return;
   	} else {
	// console.log(nav.lat + nav.lng);	
	// points.push(L.latLng(nav.lat, nav.lng));
		hotline.push([nav.lat, nav.lng, nav.alt]);
		speed.push([nav.gs]);
		altitude.push([nav.alt]);
		time.push([nav.time]);
   	
   		const marker = L.marker([nav.lat, nav.lng], {
   			icon: MapFeatures.icons.fix,
   			title: nav.title,
   		})
   		.bindPopup('<span style="font-size: 10px; text-align:left; width: 100%" align="left"><strong>Position Report Title: </strong>' + nav.name + '<br /><strong>Altitude: </strong>' + nav.alt + 'ft AMSL<strong> <br> Speed: </strong>' + nav.gs + ' GS')
   		.addTo(map);
		
   		}
   	});
   	
   } else {
   	
   	// Assuming Departure lat long to fool hotline
   	hotline.push([departure.lat, departure.lng, 0]);
   	assumed_alt = 0
   	$.each(pirep.route_details, function(i, nav) {
   	const loc = L.latLng(nav.lat, nav.lng);
   	const icon = (nav.type === 3) ? MapFeatures.icons.vor : MapFeatures.icons.fix;
   	// points.push(loc);
   	assumed_alt = assumed_alt + 5000;
   	
   	hotline.push([nav.lat, nav.lng, assumed_alt]);
   	assumed_alt++;
   	var navtype = "new";
   	if(nav.type == 2) {
   		navtype = "NDB";
   	} else if (nav.type == 3) {
   			navtype = "VOR";
   	} else if (nav.type == 4) {
   		navtype = "DME";
   	} else if (nav.type == 5) {
   		navtype = "FIX";
   	}else if (nav.type == 6) {
   		navtype = "TRACK";
   	} else {
   		navtype = "UNKNOWN";
   	}
   	
   	navfreq = "";
   	if(nav.freq != 0) {
   		navtype = "NAVAID";
   		navfreq = "<br><strong>Frequency:</strong>" + nav.freq;
   	} else {
   		navfreq = "";
   	}
   	
   	
   	
   	const marker = L.marker(loc, {
   			icon: icon,
   			title: nav.title,
   		})
   		.bindPopup('<span style="font-size: 10px; text-align:left; width: 100%" align="left"><strong>Name: </strong>' + nav.title + '(' + nav.name + ')<br /><strong>Type: </strong> ' + navtype + '' + navfreq +'</span>')
   		.addTo(map);
   });
   
   hotline.push([arrival.lat, arrival.lng, 0]);
   }
   
   points.push(arrCoords);
   
   const selPointsLayer = L.geodesic([points], {
   color: 'black',
      weight: 2,
	opacity: 1,
   }).addTo(map);
   
   console.log(speed);
   	
   	var hotlineLayer = L.hotline(hotline, hotlineOptions).addTo(map);
   	
   
   		
 
   
   map.fitBounds(selPointsLayer.getBounds());
</script>
<div class="row">
	<div class="col-md-12">
		<canvas id="flightGraph" width="350" height="150"></canvas>
	</div>
</div>
<script>


 if (speed.length === 0) {
    document.getElementById('flightGraph').style.display = 'none';
  } else {
    document.getElementById('flightGraph').style.display = 'block';
  }
  
  
var ctx = document.getElementById('flightGraph');
var myChart = new Chart(ctx, {
    type: 'line',
       data: {
           datasets: [{
        	label: "Airspeed",
			data: speed,
       lineTension: 0.3,
       fill: false,
       borderColor: 'yellow',
       backgroundColor: 'transparent',
       pointBorderColor: 'yellow',
       pointBackgroundColor: 'yellow',
       pointRadius: 1,
               // This binds the dataset to the left y axis
               yAxisID: 'left-y-axis'
           }, {
               label: "Altitude",
       data: altitude,
       lineTension: 0.3,
       fill: false,
       borderColor: 'red',
       backgroundColor: 'transparent',
       pointBorderColor: 'red',
       pointBackgroundColor: 'red',
       pointRadius: 1,
   
               // This binds the dataset to the right y axis
               yAxisID: 'right-y-axis'
           }],
           labels: time
       },
       options: {
       	responsive: true,
                   hoverMode: 'index',
                   stacked: false,
                   title:{
                       display: true,
                       text:'Flight Data Chart'
                   },
           scales: {
               yAxes: [{
                   id: 'left-y-axis',
                   type: 'linear',
                   position: 'left'
               }, {
                   id: 'right-y-axis',
                   type: 'linear',
                   position: 'right'
               }]
           }
       }
});
</script>