/*
 * Plugin Geo Map
 */
"use strict";

$$.gmap = new function() {
	const debug = $$.debug("gmap");

	let marker;

	const init = (id, processId, location, save, l10n) => {
		const tokens = location.split(',');
		const latLng = new google.maps.LatLng(tokens[0], tokens[1]);

		const map = new google.maps.Map(document.getElementById(id), {
			center : latLng,
			zoom : 12,
			mapTypeId : 'hybrid',
			fullscreenControl : false,
			streetViewControl : false,
			rotateControl : false
		});

		addMarker(latLng, map);

		map.addListener('click', (e) => {
			addMarker(e.latLng, map);
		});

		if (save) {
			const controlDiv = control(processId, l10n);
			controlDiv.index = 1;
			map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlDiv);
		}
	}

	const addMarker = (location, map) => {
		if (marker != null) {
			marker.setMap(null);
			marker = null;
		}
		marker = new google.maps.Marker({
			map : map,
			draggable : true,
			position : location
		});
		marker.addListener('click', toggleBounce)
		map.panTo(location);
	}

	const toggleBounce = () => {
		if (marker.getAnimation() !== null) {
			marker.setAnimation(null);
		} else {
			marker.setAnimation(google.maps.Animation.BOUNCE);
		}
	}

	const control = (processId, l10n) => {
		const controlDiv = document.createElement('div');
		controlDiv.classList.add('pt1');

		const button = document.createElement('button');
		button.classList.add('btn-white');
		button.innerHTML = l10n.buttonText;
		button.title = l10n.buttonTitle;

		controlDiv.appendChild(button);

		button.addEventListener('click', () => {
			$$.ajax.post('/user/plugin/gmap/process.do?method=save&id=' + processId + '&value=' + marker.getPosition().toUrlValue());
		});

		return controlDiv;
	}

	// public functions
	this.init = init;
}
