var map;
var lati = 1;
var longi = 1;
var array = [];
var tit = 0;
var markers = [];

function start(zone) {
	console.log(zone);
	$.ajax({
		type: "POST",
		url: "/Home/Zone/EditZone?handler=Markers",
		data: JSON.stringify(zone),
		headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (response) {
			console.log(response);
			setMarkersFromBackEnd(response);
		},
		error: function (error) {
			console.log(error)
		}
	})
}

function setMarkersFromBackEnd(points) {
	
	for (var i = 0; i < points.length; i++) {
		var point = points[i];
		let marker = new google.maps.Marker({
			position: { lat: point.latitude, lng: point.longitude },
			map: map,
			title: point.idMarker.toString(),
			draggable: true,
		});
		marker.addListener('position_changed', function () {
			changedPositionOfMarker(marker)
		});
		marker.addListener('dblclick', function () {
			deleteMarker(marker)
		})
		markers.push(marker);
		array.push([point.idMarker.toString(), point.latitude, point.longitude, point.action]);
		
	}

	tit = points[points.length - 1 ].idMarker + 1;
	map.setCenter({ lat: points[0].latitude, lng: points[0].longitude });
}

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		center: { lat: 1, lng: 1 },
		zoom: 16
	});
	console.log(document.getElementById('map'));
	map.addListener('click', function (e) {
		placeMarkerAndPanTo(e.latLng, map);
	});

}

function placeMarkerAndPanTo(latLng, map) {
	var marker = new google.maps.Marker({
		position: latLng,
		map: map,
		draggable: true,
		title: tit.toString(),
	});

	marker.addListener('position_changed', function () {
		changedPositionOfMarker(marker)
	});
	marker.addListener('dblclick', function () {
		deleteMarker(marker)
	})
	array.push([tit.toString(), marker.position.lat(), marker.position.lng(), "created"]);
	markers.push(marker);
	tit++;
	// array.push(latLng);
	console.log(array);
	map.panTo(latLng);
	// console.log(map);
}

function changedPositionOfMarker(marker) {
	array.forEach(element => {
		if (element[0] === marker.title) {
			element[1] = marker.position.lat();
			element[2] = marker.position.lng();
			if (element[3] !== "created") {
				element[3] = "updated";
			}
		}
	});
}

function print() {
	console.log(array);
}

function deleteMarker(marker) {
	for (let index = 0; index < markers.length; index++) {
		const element = markers[index];
		if (element.title === marker.title) {
			markers[index].setMap(null);
			markers.splice(index, 1);
		}
	}
	for (var i = 0; i < array.length; i++) {
		const element = array[i];
		if (element[0] === marker.title) {
			element[3] = "deleted";
		}
	}
}

function update(id) {
	let title = $("#zoneTitle").val();
	if (title) {
		if (markers.length >= 3) {
			$.ajax({
				type: "POST",
				url: "/Home/Zone/EditZone?handler=EditZone",
				data: JSON.stringify(createPost(title, id)),
				headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function () {
					window.location.href = "/Home/Zone/Overwiev";
				},
			})
		} else {
			alert("At least 3 markers are required.")
		}
	} else {
		alert("Zone should have a title.")
	}
}

function createPost(name, id) {
	let ret;
	var Points = [];
	array.forEach(item => {
		Points.push(Point = {
			IdMarker: item[0],
			Latitude: item[1],
			Longitude: item[2],
			Action: item[3],
			DateTime: new Date(),
			LocationName: ""
		})
	});
	ret = {
		Name: name,
		Identificator: id.toString(),
		Points: Points
	};
	return ret;
}

function back() {
	window.location.href = "/Home/Zone/Overwiev";
}

$(document).ready(function () {
	$("#partID").text("Zone");
	$("#sectionID").text("Edit");
})