<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Behavior\HasGeocoder;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Geocoder\Query\GeocodeQuery;
use Psr\Http\Client\ClientInterface;

class GeocoderSubscriber implements EventSubscriber
{
    private $apiKey;
    private $client;

    public function __construct($apiKeyServerGooglemap,ClientInterface $client)
    {
        $this->apiKey = $apiKeyServerGooglemap;
        $this->client = $client;
    }

    public function getSubscribedEvents()
    {

        return [
            Events::prePersist,
            Events::preUpdate,
        ];
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof HasGeocoder) {
            $coordinates = $this->geocoder($entity);
            if ($coordinates)
            {
                $entity->setLat($coordinates->getLatitude());
                $entity->setLng($coordinates->getLongitude());
            }

        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof HasGeocoder) {
            $coordinates = $this->geocoder($entity);
            if ($coordinates)
            {
                $entity->setLat($coordinates->getLatitude());
                $entity->setLng($coordinates->getLongitude());
            }
        }
    }

    private function geocoder(HasGeocoder $geocodable)
    {
        $provider   = new \Geocoder\Provider\GoogleMaps\GoogleMaps($this->client, null, $this->apiKey);
        $geocoder   = new \Geocoder\StatefulGeocoder($provider, 'en');
        $result     = $geocoder->geocodeQuery(GeocodeQuery::create($geocodable->getAddress().' '.$geocodable->getPostal().' '.$geocodable->getCity().' '.$geocodable->getCountry()));
        if ($result->isEmpty()) {

            return null;
        }

        return $result->first()->getCoordinates();
    }
}
