<?php

declare(strict_types=1);

namespace App\DataProvider\Utils;

use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use ApiPlatform\Core\Identifier\CompositeIdentifierParser;
use App\ApiResources\Utils\GpsCoordinate;
use App\Service\Utils\GpsCoordinateUtils;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class GpsCoordinateSearchingDataProvider : custom provider pour assurer l'alimentation de la ressource GpsCoordinate
 * @package App\DataProvider\Utils
 */
final class GpsCoordinateSearchingDataProvider implements ItemDataProviderInterface, CollectionDataProviderInterface, RestrictedDataProviderInterface
{
    public function __construct(
        private GpsCoordinateUtils $gpsCoordinateUtils,
        private RequestStack $requestStack
    )
    { }

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return GpsCoordinate::class === $resourceClass;
    }

    public function getCollection(string $resourceClass, string $operationName = null): iterable
    {
        $request = $this->requestStack->getCurrentRequest();
        $responses = [];
        try{
            $addresses = $this->gpsCoordinateUtils->searchGpsCoordinates(
                $request->get('street'),
                $request->get('cp'),
                $request->get('city')
            );
            foreach ($addresses as $address){
                $responses[] = $this->gpsCoordinateUtils->createGpsCoordinate($address);
            }
        }catch (\Exception $exception){
            $responses[] = new GpsCoordinate();
        }
        return $responses;
    }

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): GpsCoordinate
    {
        $ids = CompositeIdentifierParser::parse($id);
        try{
            $address = $this->gpsCoordinateUtils->reverseGpsCoordinates(floatval($ids['latitude']), floatval($ids['longitude']));
            $gpsCoordinateResponse = $this->gpsCoordinateUtils->createGpsCoordinate($address);
        }catch (\Exception $exception){
            $gpsCoordinateResponse = new GpsCoordinate();
        }
        return $gpsCoordinateResponse;
    }
}