<?php

namespace AutoAdmin\Bundle\Media\Serializer;



use AutoAdmin\Bundle\Media\Model\Library\BaseMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\BaseMediaTranslationInterface;
use AutoAdmin\Bundle\Media\Model\Library\FileMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\FileMediaTranslationInterface;
use AutoAdmin\Bundle\Media\Model\Library\ImageMediaInterface;
use AutoAdmin\Bundle\Media\Model\Library\ImageMediaTranslationInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class MediaNormalizer implements NormalizerInterface
{
    public function __construct(
        private NormalizerInterface $objectNormalizer,
    ) {
    }

    public function normalize(mixed $media, string $format = null, array $context = []): array
    {
        $data = $this->objectNormalizer->normalize($media, $format, $context);

        if($media instanceof FileMediaInterface) {
            // do nothing, handled via groups
        } elseif ($media instanceof ImageMediaInterface) {
            // do nothing, handled via groups
        }

        /** @var BaseMediaTranslationInterface $tr */
        $tr = $media->getCurrentTranslation();
        if($tr instanceof FileMediaTranslationInterface) {
            $data["fileName"] = $tr->getFileName();
            $data["title"] = $tr->getTitle();
        }
        if ($tr instanceof ImageMediaTranslationInterface) {
            $data["alt"] = $tr->getAlt();
        }

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof BaseMediaInterface && $format === 'json';
    }
}