/*
 * HTMLMapMarker Javascript class
 * Extends the Google Maps OverlayView class
 * Set up to accept our position, html for the div, and the map to attach it to as arguments
 */

const createHTMLMapMarker = ({ OverlayView = google.maps.OverlayView,  ...args }) => {
	class HTMLMapMarker extends OverlayView {
	  constructor() {
	    super();
	    this.latlng = args.position;
	    this.html = args.html;
	    this.size = args.size;
	    this.setMap(args.map);
	    this.content=args.content;
	    //console.log(this);
	  }
	
	  createDiv() {
	    this.div = document.createElement('div');
	    this.div.style.position = 'absolute';
	    if (this.html) {
	      this.div.innerHTML = this.html;
	    }
	    google.maps.event.addDomListener(this.div, 'click', event => {
	      google.maps.event.trigger(this, 'click');
	    });
	  }
	
	  appendDivToOverlay() {
	    const panes = this.getPanes();
	    panes.overlayMouseTarget.appendChild(this.div);
	  }
	
	  positionDiv() {
	    const point = this.getProjection().fromLatLngToDivPixel(this.latlng);
	    if (point) {
	      this.div.style.left = `${point.x-this.size.width}px`;
	      this.div.style.top = `${point.y-this.size.height}px`;
	    }
	  }
	
	  draw() {
	    if (!this.div) {
	      this.createDiv();
	      this.appendDivToOverlay();

		this.addListener('click', function() {
			var infowindow = new google.maps.InfoWindow({
			content: '<span>'+this.content+'</span>',
			position:this.latlng
			});

			infowindow.open(this.map, this);
		});
	    }

	    this.positionDiv();
	  }
	
	  remove() {
	    if (this.div) {
	      this.div.parentNode.removeChild(this.div);
	      this.div = null;
	    }
	  }
	
	  getPosition() {
	    return this.latlng;
	  }
	
	  getDraggable() {
	    return false;
	  }
	}

	return new HTMLMapMarker();
};