<?php

namespace App\Serializer;

use App\Entity\Prestataire;
use Sonata\MediaBundle\Provider\Pool;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * This class allows to expose the media of a Prestataire in ApiPlatform
 * (because it's not possible with a Media from SonataMediaBundle).
 */
final class ApiNormalizer implements NormalizerInterface, SerializerAwareInterface
{
    private $decorated;
    private $pool;

    public function __construct(NormalizerInterface $decorated, Pool $pool)
    {
        $this->decorated = $decorated;
        $this->pool = $pool;
    }

    public function supportsNormalization($data, $format = null)
    {
        return $this->decorated->supportsNormalization($data, $format);
    }

    public function normalize($object, $format = null, array $context = [])
    {
        $data = $this->decorated->normalize($object, $format, $context);

        // In the case of normalizing a Prestataire...
        if (!$object instanceof Prestataire) {
            return $data;
        }

        // ... we retrieve its associated Sonata Media (from the Sonata Media's provider, from the providers pool)
        if (is_array($data) && $media = $object->getMedia()) {
            if ($provider = $this->pool->getProvider($media->getProviderName())) {
                $data['media'] = $provider->getHelperProperties($media, 'reference');
            }
        }

        return $data;
    }

    public function setSerializer(SerializerInterface $serializer)
    {
        if ($this->decorated instanceof SerializerAwareInterface) {
            $this->decorated->setSerializer($serializer);
        }
    }
}
