<?php

namespace AutoAdmin\Bundle\Media\EventListener\Doctrine;

use AutoAdmin\Bundle\Media\Model\Library\FileMediaInterface;
use AutoAdmin\Bundle\Media\Upload\MediaRemoveHandler;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PreRemoveEventArgs;
use Doctrine\ORM\Events;

class MediaRemoveListener implements EventSubscriber
{
    protected array $queue = [];

    public function __construct(
        protected MediaRemoveHandler $handler
    ) {
    }

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

    public function preRemove(PreRemoveEventArgs $event)
    {
        $entity = $event->getObject();
        if ($entity instanceof FileMediaInterface && $o = $event->getObject()) {
            $this->queue[] = clone $o;
        }
    }

    public function postRemove(PostRemoveEventArgs $event)
    {
        $entity = $event->getObject();
        if ($entity instanceof FileMediaInterface) {
            foreach ($this->queue as $item) {
                $this->handler->handleRemove($item);
            }
        }
    }
}