<?php
declare(strict_types=1);

namespace App\DataProvider\Enum;

use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\ApiResources\Enum\Enum;
use App\Service\Utils\Parser;
use App\Service\Utils\Reflection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class EnumDataProvider : custom provider pour assurer l'alimentation des enums
 * @package App\DataProvider\Access
 */
final class EnumDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
{
    public function __construct(
        private Parser $parser,
        private string $opentalentConfig,
        private Reflection $reflection
    )
    { }

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

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?Enum
    {
        $enums = $this->parser->yamlParser($this->opentalentConfig, 'enum.yaml');
        $enumClass = $enums['opentalent'][$id];

        if(!$enumClass)
            throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $id));

        try{
            $items = $this->reflection->dynamicInvokeClassWithArgsAndMethod(
                $enumClass,
                'toArray'
            );
        }catch (\Exception $exception){
            throw new NotFoundHttpException(sprintf('Enum %s does\'nt exist', $id));
        }

        $enumResponse = new Enum();
        $enumResponse->setName($id);
        $enumResponse->setItems($items);
        return $enumResponse;
    }
}