<?php

namespace AutoAdmin\Bundle\Media\EventListener\Doctrine;

use AutoAdmin\Bundle\Media\Exception\MappingNotFoundException;
use AutoAdmin\Bundle\Media\Model\FileInterface;
use AutoAdmin\Bundle\Media\Upload\UploadHandlerInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\HttpFoundation\File\UploadedFile;


class UploadListener implements EventSubscriber
{
    private UploadHandlerInterface $uploadHandler;

    public function __construct(UploadHandlerInterface $uploadHandler)
    {
        $this->uploadHandler = $uploadHandler;
    }

    /**
     * The events the listener is subscribed to.
     */
    public function getSubscribedEvents(): array
    {
        return [
            Events::prePersist,
            Events::preUpdate,
        ];
    }

    /**
     * @throws MappingNotFoundException
     */
    public function prePersist(LifecycleEventArgs $event): void
    {
        $object = $event->getObject();
        if ($object instanceof FileInterface) {
            $this->uploadHandler->handle($object);
        }
    }

    /**
     * @throws MappingNotFoundException
     */
    public function preUpdate(LifecycleEventArgs $event): void
    {
        $object = $event->getObject();
        if (
            $object instanceof FileInterface
            && ($file = $object->getFile())
            && $file instanceof UploadedFile
        ) {
            $this->uploadHandler->handle($object);
        }
    }
}
