const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
editor_mode = urlParams.has('editor');

if (editor_mode) {
	var editor_mode_polygon = urlParams.has('polygon');
	
	var draw_layer;
	var polyline;

	var edit_active = 0;
	
	var editor_style = {
		radius: 8,
		fillColor: "#00ff00",
		color: "red",
		opacity: 1.0,
		fillOpacity: 0.5
	};

	function start_editing(dir = 1) {
		// TODO: Check whether we already are in edit mode
		// TODO: Detect whether we are cloner to the tail or the head, and issue Fwd or Bwd accordingly
		if (polyline) {
			if (dir)
				polyline.editor.continueForward();
			else
				polyline.editor.continueBackward();
		} else {
			if (editor_mode_polygon)
				polyline = mymap.editTools.startPolygon();
			else
				polyline = mymap.editTools.startPolyline();
		}
	}

	function start_reverse_editing() {
		start_editing(0);
	}

	function strToPoints(str) {
		var temp = JSON.parse("[" + str + "]"); // TODO: add .5 everwhere
		return temp;
	}

	function onDragEnd(e) {
		if (!polyline)
			return;
		var latlngs = polyline.getLatLngs();

		for (var i = 0; i < latlngs.length; i++) {
			latlngs[i] = resolve_latlng(latlngs[i], 1);
		}
		polyline.editor.refresh();
		polyline.editor.refreshVertexMarkers();
		location.hash = get_location_string();
	}

	function onLoad(interactive = 1) {
		if (interactive) {
			str = prompt("Instructions: \n" +
			"* Click the scribble-icon in the top left to start or continue drawing.\n" +
			"* Click last waypoint to stop drawing.\n" +
			"* Click a waypoint to delete it.\n" +
			"* Click save in the top right to get the new string.\n\n" +
			"Enter existing waypoints in the following format: [x,y],[x,y]:", window.location.hash.slice(1));
			if (str == undefined)
				return;
		} else {
			str = window.location.hash.slice(1);
		}

		if (polyline) {
				polyline.remove(mymap);
				polyline = undefined;
		}

		if (str) {
			coords = strToPoints(str);
			for (var i = 0; i < coords.length; i++) {
				coords[i] = [coords[i][1], coords[i][0]];
			}
			if (editor_mode_polygon)
				polyline = L.polygon([coords], editor_style).addTo(mymap);
			else
				polyline = L.polyline(coords, editor_style).addTo(mymap);
			// polyline.on('dragend', onDragEnd); // TODO: Doesn't work, see "workaround" below
			polyline.enableEdit();
			if (interactive) {
				latlng = L.latLng(polyline_get_middle_coords(coords));
				jump_to(latlng, 8);
			}
		}
	}

	function editor_onHashChange() {
		if (("#" + get_location_string()) != window.location.hash) {
			onLoad(0);
		}
	}

	window.removeEventListener("hashchange", onHashChange, false);
	window.addEventListener("hashchange", editor_onHashChange, false);
	window.addEventListener("mouseup", onDragEnd, false); // Workaround as polyline.on(dragend, ) doesn't seem to work

	function onMapKeydown(e) {
		if (e.originalEvent.key == "Escape") {
			if (polyline)
				polyline.editor.cancelDrawing();
		}
	}

	// Configure map for better editing
	mymap.setMaxZoom(14);
	mymap.off('click', onMapClick);
	mymap.on('keydown', onMapKeydown);

	function get_location_string() {
		var latlngs;
		if (editor_mode_polygon)
			latlngs = polyline.getLatLngs()[0];
		else
			latlngs = polyline.getLatLngs();
		var str = "";

		for (var i = 0; i < latlngs.length; i++) {
			latlng = resolve_latlng(latlngs[i], 1);
			if (i != 0)
				str += ",";
			str += "[" + (latlng.lng) + "," + (latlng.lat) + "]";
		}

		return str;
	}

	function show_location_string(e) {
		if (polyline)
			polyline.editor.cancelDrawing();
		prompt("Copy this string back into the Wiki and wait for the server to refresh the maps:", get_location_string());
	}

	function reset_path(e) {
		onLoad(1);
	}

	L.EditControl = L.Control.extend({
		options: {
			position: 'topleft',
			callback: null,
			kind: '',
			html: ''
		},
		onAdd: function (map) {
			var container = L.DomUtil.create('div', 'leaflet-control leaflet-bar'),
			link = L.DomUtil.create('a', '', container);

			link.href = '#';
			link.title = this.options.title;
			link.innerHTML = this.options.html;
			L.DomEvent.on(link, 'mousedown', L.DomEvent.stop);
			L.DomEvent.on(link, 'mouseup', L.DomEvent.stop);
			L.DomEvent.on(link, 'click', L.DomEvent.stop)
			.on(link, 'click', function (e) {
				window.LAYER = this.options.callback.call(map.editTools);
			}, this);
		return container;
		}
	});

	L.ResetPathControl = L.EditControl.extend({
		options: {
			position: 'topleft',
			callback: reset_path,
			title: 'Enter path coordinates',
			html: '📂'
		}
	});

	L.StartEditControl = L.EditControl.extend({
		options: {
			position: 'topleft',
			callback: start_editing,
			title: 'Start editing (forward)',
			html: '\\/\\'
		}
	});

	L.StartReverseEditControl = L.EditControl.extend({
		options: {
			position: 'topleft',
			callback: start_reverse_editing,
			title: 'Start editing (backward)',
			html: '↺'
		}
	});

	L.NewLineControl = L.EditControl.extend({
		options: {
			position: 'topleft',
			callback: show_location_string,
			title: 'Get location string',
			html: '💾'
		}
	});

	mymap.addControl(new L.NewLineControl());
	mymap.addControl(new L.ResetPathControl());
	mymap.addControl(new L.StartEditControl());
	mymap.addControl(new L.StartReverseEditControl());

	onLoad();
}