<?php
namespace Medienreaktor\Persons\Service;

use TYPO3\CMS\Core\Configuration\ConfigurationManager;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * PersonDatabaseService
 */
class GoogleGeoCodeService implements \TYPO3\CMS\Core\SingletonInterface {

    // Google geo Code API URL
    protected $apiEndpoint = 'https://maps.googleapis.com/maps/api/geocode/json';


    /**
     * Get all persons
     *
     * @return array
     */
    public function getGeoCodesByZip($zip)
    {
        $request = '&address='.$zip;
        return $this->apiCall($request);;
    }

    /**
     * Call person database web service
     *
     * @param string $request
     * @return array
     */
    protected function apiCall($request)
    {
        $configurationManager = Generalutility::makeInstance(ConfigurationManager::class);
        $typoscript = $configurationManager->getConfiguration(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT,'Persons','Map');

        $apiEndpoint = $this->apiEndpoint.'?key='.$typoscript["plugin."]["tx_persons_persons."]["settings."]["googleMapsAPIKey"];

        /*
        if($settings['zipSearchCountry']) {
            $request = $request.' '.$settings['zipSearchCountry'];
        }
        */

        return $this->rawApiCall($apiEndpoint.$request);
    }

    /**
     * Call person database web service (raw API call)
     *
     * @param string $request
     * @return array
     */
    protected function rawApiCall($request)
    {
        $response = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($request);
        return json_decode($response, TRUE);
    }


}
