<?php

namespace FiloBlu\Storelocator\Block\Adminhtml\Stores\Form\Renderer\Fieldset;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Renderer\Fieldset\Element;
use Magento\Framework\Data\Form\Element\Renderer\RendererInterface;
use Magento\Framework\Locale\Resolver;
use Magento\Framework\UrlInterface;

/**
 * Form fieldset renderer
 */
class GoogleMap extends Element implements RendererInterface
{

    const CONFIG_IMAGE_DIR_PREFIX = 'filoblu/storelocator/';
    protected $_template = 'stores/form/renderer/fieldset/google_map.phtml';
    private $helper;
    /**
     * @var Resolver
     */
    private $localeResolver;

    /**
     * @param Context $context
     * @param Data $helper
     * @param Resolver $localeResolver
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $helper,
        Resolver $localeResolver,
        array $data = []
    ) {
        $this->helper = $helper;
        parent::__construct($context, $data);
        $this->localeResolver = $localeResolver;
    }

    /**
     *
     */
    public function getJsonMapConfig()
    {
        return json_encode([
            'center'                 => [
                'lat' => (float)$this->getElement()->getLatitude(),
                'lng' => (float)$this->getElement()->getLongitude()
            ],
            'mapContainerId'         => 'map',
            'gmapMarkersMarkerImage' => ($this->helper->getConfig(
                'filoblu_storelocator_section/markers/gmaps_markers_marker_image'
            ) ? $this->getBaseUrlConfigImage() . $this->helper->getConfig(
                'filoblu_storelocator_section/markers/gmaps_markers_marker_image'
            ) : ''),
            'gmapStoresImageDir'     => $this->getBaseUrlStoresImage()
        ]);
    }

    protected function getBaseUrlConfigImage()
    {
        return $this->_storeManager->getStore()->getBaseUrl(
            UrlInterface::URL_TYPE_MEDIA
        ) . self::CONFIG_IMAGE_DIR_PREFIX;
    }

    /**
     * @return string
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getGoogleMapsApiUrl()
    {
        $language = explode('_', $this->localeResolver->getLocale())[0];
        $apiKey = $this->helper->getConfig('filoblu_storelocator_section/general/gmaps_api_key');
        $apiUrl = $this->helper->getConfig('filoblu_storelocator_section/general/gmaps_api_url');

        return sprintf(
            '%s?language=%s&key=%s&libraries=places',
            $apiUrl,
            $language,
            $apiKey
        );
    }


    /**
     * @return Data
     */
    public function getHelper(): Data
    {
        return $this->helper;
    }
}
