<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 25.01.24
 */


namespace App\Serializer;


use App\Entity\Document;
use App\Entity\DocumentObject;
use App\Entity\MediaObject;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Vich\UploaderBundle\Storage\StorageInterface;

#[AsDecorator('api_platform.jsonld.normalizer.item')]
final class MediaObjectNormalizer implements NormalizerInterface, SerializerAwareInterface
{
    private const ALREADY_CALLED = 'MEDIA_OBJECT_NORMALIZER_ALREADY_CALLED';

    public function __construct(
        private StorageInterface $storage,
        private NormalizerInterface $normalizer
    )
    {
    }

    public function normalize($object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
    {
        $context[self::ALREADY_CALLED] = true;

        if ($object instanceof MediaObject || $object instanceof DocumentObject) {
            // Nur für MediaObject die URI generieren
            $object->contentUrl = $this->storage->resolveUri($object, 'file');
        }

        return $this->normalizer->normalize($object, $format, $context);
    }

    public function supportsNormalization($data, ?string $format = null, array $context = []): bool
    {
        if (isset($context[self::ALREADY_CALLED])) {
            //return false;
        }
       // return $data instanceof MediaObject;
        return $this->normalizer->supportsNormalization($data, $format, $context);
    }

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

    public function getSupportedTypes(?string $format): array
    {
        if (method_exists($this->normalizer, 'getSupportedTypes')) {
            return $this->normalizer->getSupportedTypes($format);
        }

        return 'jsonld' === $format ? ['*' => true] : [];
    }
}