<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormFieldViewHelper;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Page\AssetCollector;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;

/**
 * Google Map
 */
class MapViewHelper extends AbstractFormFieldViewHelper
{
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('showSearch', 'boolean', 'Show a geocoder Field', false, true);
        $this->registerArgument('autoSearch', 'string', 'List of fields', false, '');
        $this->registerArgument('default', 'string', 'Default Value');
        $this->registerArgument('placeholder', 'string', 'The placeholder for the input', false, '');
        $this->registerArgument('buttonLabel', 'string', 'The label for the search button', false, 'Suche');
        $this->registerArgument('id', 'string', 'The id for the input', false, '');

        $this->registerArgument('zoom', 'int', 'Default Zoom Level', false, 7);
        $this->registerArgument('latitude', 'double', 'The latitude of the map center', false, 0);
        $this->registerArgument('longitude', 'double', 'The longitude of the map center', false, 0);
        $this->registerArgument('latlng', 'string', 'latitude,longitude of the map center', false, 0);
        $this->registerArgument('apiUrl', 'string', 'Google Maps API', false, 'https://maps.googleapis.com/maps/api/js?v=3');
        $this->registerArgument('apiKey', 'string', 'Google Maps API Key', false, '');


        $this->registerArgument('panControl', 'bool', 'pan control', false, true);
        $this->registerArgument('zoomControl', 'bool', 'zoom control', false, true);
        $this->registerArgument('scaleControl', 'bool', 'scale control', false, true);
        $this->registerArgument('mapTypeControl', 'bool', 'map type control', false, false);
        $this->registerArgument('streetViewControl', 'bool', 'streetview control', false, false);
        $this->registerArgument('overviewMapControl', 'bool', 'show overview map', false, false);
        $this->registerArgument('scrollwheel', 'bool', 'scrollwheel activated to zoom the map', false, false);

        //$this->registerArgument('mapType', 'string', 'The type of the map', false, 'MapTypeId.ROADMAP');
    }

    /**
     * Render the tag.
     *
     * @return string rendered tag.
     * @api
     */
    public function render(): string
    {
        $this->registerFieldNameForFormTokenGeneration($this->getName());
        $settings = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS, 'IgGooglemaps', 'Maps');
        if ($this->arguments['apiKey']) {
            $apiKey=$this->arguments['apiKey'];
        } elseif ($settings['apiKey']) {
            $apiKey=$settings['apiKey'];
        } else {
            if (class_exists(ExtensionConfiguration::class)) {
                $extConf = GeneralUtility::makeInstance(
                    ExtensionConfiguration::class
                )->get('ig_googlemaps');
                $apiKey=$extConf['googleMapsGeocodingApiKey'];
            } else {
                // TYPO3 8.7
                $extConf=unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['ig_googlemaps']);
                $apiKey=$extConf['googleMapsGeocodingApiKey'];
            }
        }
        $assetCollector = GeneralUtility::makeInstance(AssetCollector::class);
        $assetCollector->addJavaScript('ig_datapool_fe_googlemaps_apiUrl', $this->arguments['apiUrl'] . '&key=' . $apiKey);

        $value = [0, 0];
        $hasValue = 0;
        if ($this->getValueAttribute() != null) {
            $valueLatLng = GeneralUtility::trimExplode(',', $this->getValueAttribute(), true);
            $value=[
                'lat' => $valueLatLng[0],
                'lng' => $valueLatLng[1]
            ];
            $hasValue = 1;
        } else {
            if ($this->arguments['latlng']) {
                $lat = $lng = null;
                //first priority: commaseparated string or array
                if (is_array($this->arguments['latlng'])) {
                    if (isset($this->arguments['latlng']['lat'])) {
                        $lat = $this->arguments['latlng']['lat'];
                        $lng = $this->arguments['latlng']['lng'];
                    } else {
                        $lat = $this->arguments['latlng'][0];
                        $lng = $this->arguments['latlng'][1];
                    }
                } else {
                    [$lat, $lng] = GeneralUtility::trimExplode(',', $this->arguments['latlng'], true);
                }
                $value=[
                'lat' => $lat,
                'lng' => $lng
                ];
            } else {
                $value=[
                'lat' => $this->arguments['latitude'],
                'lng' => $this->arguments['longitude']
                ];
            }
            //$value = GeneralUtility::trimExplode(',', $this->arguments['defaultPosition'], true);
        }

        $res = '<div class="gmap"></div>';
        if ($this->arguments['showSearch']) {
            $res .= '
                <div class="geoCoderWrapper"  >
                <div class="ig-inline ym-g80">
                    <input class="geocoderSearch" id="' . $this->arguments['id'] . '" type="text" value="" placeholder="' . $this->arguments['placeholder'] . '" />
                </div><div class="ig-inline ym-g20">
                    <button class="geocoderButton link-button" type="button" onclick="return false" class="dp-button geocoderButton">' . $this->arguments['buttonLabel'] . '</button></div>
                </div>';
        }

        $res .= '<input type="hidden" name="' . $this->getName() . '" value="' . $this->getValueAttribute() . '" />';

        $autoSearch = '';
        if ($this->arguments['autoSearch']) {
            $asPrefix = '#' . substr((string) $this->arguments['id'], 0, strrpos((string) $this->arguments['id'], '-') + 1);
            $temp = GeneralUtility::trimExplode(',', $this->arguments['autoSearch'], true);
            foreach ($temp as &$val) {
                $val = $asPrefix . $val;
            }

            $autoSearch = ' data-autosearch="' . implode(',', $temp) . '" ';
        }
        $controls='';
        $controls.=' data-pan-control="'.($this->arguments['panControl'] ? 'true' : 'false').'"';
        $controls.=' data-zoom-control="'.($this->arguments['zoomControl'] ? 'true' : 'false').'"';
        $controls.=' data-scale-control="'.($this->arguments['scaleControl'] ? 'true' : 'false').'"';
        $controls.=' data-map-type-control="'.($this->arguments['mapTypeControl'] ? 'true' : 'false').'"';
        $controls.=' data-street-view-control="'.($this->arguments['streetViewControl'] ? 'true' : 'false').'"';
        $controls.=' data-overview-map-control="'.($this->arguments['overviewMapControl'] ? 'true' : 'false').'"';
        $controls.=' data-scrollwheel="'.($this->arguments['scrollwheel'] ? 'true' : 'false').'"';
        //  data-map-type="google.maps.'.( $this->arguments['mapType'] ?? 'MapTypeId.ROADMAP').'"
        return '<div class="dp-map-input" ' . $autoSearch . ' data-zoom="' . intval($this->arguments['zoom']) . '" data-lat="' . floatval($value['lat']) . '" data-lng="' . floatval($value['lng']) . '" data-hasMarker="' . $hasValue . '"' . $controls . '>' . $res . '</div>';
    }
}
