<?php

namespace AutoAdmin\Bundle\Media\EventListener\Doctrine;

use AutoAdmin\Bundle\Media\Model\AbstractFile;
use AutoAdmin\Bundle\Media\Upload\UploadHandlerInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class RemoveListener implements EventSubscriber
{
    protected UploadHandlerInterface $handler;
    protected array $queue = [];

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

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

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

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