var map;
var deviceMarkers = [];
var gPolygon;
function getLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition);
	}
}
function showPosition(position) {
	lati = position.coords.latitude;
	longi = position.coords.longitude;
	console.log(lati + " " + longi);
	initMap(lati, longi);
}
function initMap(lati, longi) {
	map = new google.maps.Map(document.getElementById('map'), {
		center: { lat: lati, lng: longi },
		zoom: 16
	});
}

function show() {
	if ($("#selectDevice option:selected").val() !== "null") {
		clearMarkers();
		$.ajax({
			type: "POST",
			data: JSON.stringify( buildPost() ),
			url: "/Home/Home?handler=Device",
			headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (response) {
				setCenterMap(response);
				console.log(response);
			},
		})
	} else {
		alert("Please select device")
	}
}

function buildPost() {
	let ret = {
		Identificator: $("#selectDevice option:selected").val().toString(),
		DateFrom: $("#dateFrom").val(),
		DateTo: $("#dateTo").val()
	}
	return ret;
}

function setCenterMap(data) {
	if (data.deviceMarkers.length != 0) {
		map.setCenter({ lat: data.deviceMarkers[data.deviceMarkers.length - 1].latitude, lng: data.deviceMarkers[data.deviceMarkers.length - 1].longitude });
		if (data.zoneMarkers.length != 0) {
			for (var i = 0; i < data.zoneMarkers.length; i++) {
				setZoneMarkers(data.zoneMarkers[i]);
			}
		}
		setDeviceMarks(data.deviceMarkers);
	} else {
		if (data.zoneMarkers.length != 0) {
			for (var i = 0; i < data.zoneMarkers.length; i++) {
				setZoneMarkers(data.zoneMarkers[i]);
			}
			
		}
	}
}

function setDeviceMarks(device) {
	for (var i in device) {
		let date = device[i].dateTime.substring(0, 10);
		let time = device[i].dateTime.substring(11, 19);
		let marker = new google.maps.Marker({
			position: { lat: device[i].latitude, lng: device[i].longitude },
			map: map,
			title: time + " " + date,
			icon: {
				path: google.maps.SymbolPath.CIRCLE,
				scale: 5
			},
			draggable: false,
		})
		deviceMarkers.push(marker);
	}
}

function setZoneMarkers(zone) {
	let polygon = []
	for (var i in zone) {
		polygon.push(
			new google.maps.LatLng(zone[i].latitude, zone[i].longitude)
		);
	}
	gPolygon = new google.maps.Polygon({
		paths: polygon,
		strokeColor: "#FF0000",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#FF0000",
		fillOpacity: 0.35
	});
	gPolygon.setMap(map)
}

function clearMarkers() {
	for (var i = 0; i < deviceMarkers.length; i++) {
		deviceMarkers[i].setMap(null);
	}
	if (gPolygon) {

		gPolygon.setMap(null);
	}
}

$(document).ready(function () {
	$("#partID").text("Home");
	$("#sectionID").text("Main visualization");
})

$('#selectDevice').scombobox({
	fullMatch: true
});