<?php

namespace AutoAdmin\Bundle\Cache\EventListener;

use AutoAdmin\Bundle\Cache\Service\CacheService;
use AutoAdmin\Bundle\Cache\Entity\CacheRule;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Doctrine\Common\EventSubscriber;


class CacheRuleEventListener implements EventSubscriber
{
    private CacheService $service;

    public function __construct(CacheService $service)
    {
        $this->service = $service;
    }

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

    public function postPersist(LifecycleEventArgs $event): void
    {
        $object = $event->getEntity();
        if ($object instanceof CacheRule) {
            $this->regenerateCachedRules();
        }
    }

    public function postUpdate(LifecycleEventArgs $event): void
    {
        $object = $event->getEntity();
        if ($object instanceof CacheRule) {
            $this->regenerateCachedRules();
        }
    }

    public function postRemove(LifecycleEventArgs $event): void
    {
        $object = $event->getEntity();
        if ($object instanceof CacheRule) {
            $this->regenerateCachedRules();
        }
    }

    private function regenerateCachedRules(): void
    {
        $this->service->regenerateCachedRules();
        $this->service->getCacheRules();
    }
}
