<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


use AutoAdmin\Bundle\Content\Cache\StaticTranslationCacheHandler;
use AutoAdmin\Bundle\Content\Entity\StaticText;
use AutoAdmin\Bundle\Content\Entity\StaticTextTranslation;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Doctrine\ORM\Events;

class StaticTranslationSubscriber implements EventSubscriber
{
    public function __construct(
        private StaticTranslationCacheHandler $cacheHandler,
        private array $queued = [],
    ) {
    }

    public function getSubscribedEvents(): array
    {
        return array(
            // detect altered entity to program cache reset
            Events::postPersist,
            Events::postUpdate,
            Events::postRemove,

            // cache reset event
            Events::postFlush,
        );
    }

    public function postPersist(PostPersistEventArgs $args): void
    {
        $this->queueIfStaticTranslation($args);
    }

    public function postUpdate(PostUpdateEventArgs $args): void
    {
        $this->queueIfStaticTranslation($args);
    }

    public function postRemove(PostRemoveEventArgs $args): void
    {
        $this->queueIfStaticTranslation($args);
    }

    public function queueIfStaticTranslation(PostPersistEventArgs|PostUpdateEventArgs|PostRemoveEventArgs $args): void
    {
        $object = $args->getObject();
        if (
            $object instanceof StaticText
            || $object instanceof StaticTextTranslation
        ) {
            $this->queued[] = $object;
        }
    }

    public function postFlush(PostFlushEventArgs $args): void
    {
        if (!empty($this->queued)) {
            // this operation must be properly done, we reset all translations cache on save/update
            $this->cacheHandler->saveValue();
            $this->queued = [];
        }
    }
}
