<?php
namespace Medienreaktor\Products\ViewHelpers\Map;

class CanvasViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper {

	/**
	* Arguments Initialization
	*/
	public function initializeArguments(): void {
		$this->registerArgument('id', 'String', 'The ID of the canvas element', TRUE);
		$this->registerArgument('latitude', 'String', 'The latitude for the map center', TRUE);
		$this->registerArgument('longitude', 'String', 'The longitude for the map center', TRUE);
		$this->registerArgument('zoom', 'String', 'The zoom factor', TRUE);
	}

     /**
     * Render method
     * @return string
     */
    public function render() {
		$id		 	= $this->arguments['id'];
		$latitude	= $this->arguments['latitude'];
		$longitude	= $this->arguments['longitude'];
		$zoom		= $this->arguments['zoom'];
		$settings	= $this->templateVariableContainer->get('settings');

		if($settings["googleApiKey"])
		{
			$output = '<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&key='.$settings["googleApiKey"].'"></script>';
		}
		else
		{
			$output = '<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>';
		}

		$output .= '<script type="text/javascript">';
			$output .= '
				var mapOptions = {
					center: new google.maps.LatLng('.$latitude.', '.$longitude.'),
					zoom: '.$zoom.',
                    maxZoom: '.($zoom+2).',
					mapTypeId: google.maps.MapTypeId.ROADMAP
				};
				var map = new google.maps.Map(document.getElementById("'.$id.'"), mapOptions);

				var markers = [];
				var infowindow = new google.maps.InfoWindow();
			';
			$output .= $this->renderChildren();
            $output .= '
                var bounds = new google.maps.LatLngBounds();
                for (var i = 0; i < markers.length; i++) {
                    bounds.extend(markers[i].getPosition());
                }

                map.fitBounds(bounds);
            ';
		$output .= '</script>';

		return $output;
    }

}
