import './style.scss';

var gmapsIsLoaded = false;

export default new Class({
	Extends: Hedera.Form,
	Template: require('./ui.xml')

	,locations: null

	,async activate() {
		this.gui.loaderPush();

		var sql = 'SELECT lat, lng, title, address, postcode, city, province, phone, language FROM location';
		const resultSet = await this.conn.execQuery(sql);
		this.locations = resultSet.fetchData();
	
		if (!gmapsIsLoaded) {
			window.gmapsLoadedCallback = () => this.gmapsLoaded();
			Vn.includeJs('https://maps.google.com/maps/api/js'
				+'?sensor=false&callback=gmapsLoadedCallback'
				+'&key=AIzaSyBbunFsAFEkjtw-c7BUHNgkThSlKEKFxiE',
				null, true
			);
		} else
			this.gmapsLoaded();
	}

	,gmapsLoaded() {
		this.gui.loaderPop();
		gmapsIsLoaded = true;

		if (!this.locations || !gmapsIsLoaded)
			return;

		var options = {
			 zoom: 4
			,mapTypeId: google.maps.MapTypeId.ROADMAP
			,center: new google.maps.LatLng(46.0, 4.0)
		};

		var div = this.$.form;
		var gmap = new google.maps.Map(div, options);

		for (const location of this.locations)
			this.createMarker(location, gmap);
	}
	
	,createMarker(location, gmap) {
		var div = document.createElement('div');
		div.className = 'marker';

		var h = document.createElement('h3');
		h.appendChild(document.createTextNode(location.title));
		div.appendChild(h);

		var p = document.createElement('p');
		p.appendChild(document.createTextNode(location.address));
		div.appendChild(p);

		var p = document.createElement('p');
		p.appendChild(document.createTextNode(location.postcode +' '+ location.city));
		div.appendChild(p);

		var p = document.createElement('p');
		p.appendChild(document.createTextNode(location.province));
		div.appendChild(p);

		var p = document.createElement('p');
		p.appendChild(document.createTextNode(location.phone));
		div.appendChild(p);
		
		var lat = new google.maps.LatLng(
			location.lat,
			location.lng
		);

		var marker = new google.maps.Marker({
			 position: lat
			,tilte: location.title
			,map: gmap
		});

		var infoWindow = new google.maps.InfoWindow({
			 content: div
		});

		google.maps.event.addListener(marker, 'click',
			this.openInfoWindow.bind(this, infoWindow, gmap, marker));
 		
 		if (Vn.Locale.language
		&& Vn.Locale.language == location.language)
 			this.openInfoWindow(infoWindow, gmap, marker);
	}
	
	,openInfoWindow(infoWindow, gmap, marker) {
		if (this.openedWindow)
			this.openedWindow.close();

		infoWindow.open(gmap, marker);
		this.openedWindow = infoWindow;
	}
});
