<?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\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(LifecycleEventArgs $args): void
    {
        $this->queueIfStaticTranslation($args);
    }

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

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

    public function queueIfStaticTranslation(LifecycleEventArgs $args)
    {
        $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 = [];
        }
    }
}
