<?php
namespace App\EventListener;

use App\Entity\Adherent;
use App\Entity\EntityTrait\GeolocEntityTrait;
use App\Entity\Geoloc;
use App\Entity\Prestataire;
use App\Entity\User;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;

class GeolocListener
{
    public function preUpdate(PreUpdateEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();

        if (!($entity instanceof Geoloc) || ($entity instanceof Geoloc) && !($eventArgs->hasChangedField('adresse') || $eventArgs->hasChangedField('cpostal') || $eventArgs->hasChangedField('ville') || $eventArgs->hasChangedField('lat') || $eventArgs->hasChangedField('lon'))) {
            return;
        }
        // GEOCODING ADDRESS :
        $httpClient = new \Http\Adapter\Guzzle6\Client();
        $provider = Nominatim::withOpenStreetMapServer($httpClient, 'Mozilla/5.0');
        $geocoder = new \Geocoder\StatefulGeocoder($provider, 'fr');
        $fullAddress = $entity->getAdresse().' '.$entity->getCpostal().' '.$entity->getVille();
        // Query geocoding from complete addresse
        $result = $geocoder->geocodeQuery(GeocodeQuery::create($fullAddress));
        if (count($result) > 0) {
            $coords = $result->first()->getCoordinates();
            $entity->setLat($coords->getLatitude());
            $entity->setLon($coords->getLongitude());
        }
    }
}
