<?php

namespace AutoAdmin\Bundle\Content\EventListener;

use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;

class CurrentTranslationLoader implements EventSubscriber
{
    private EntityTranslator $entityTranslator;

    public function __construct(EntityTranslator $entityTranslator)
    {
        $this->entityTranslator = $entityTranslator;
    }

    public function getSubscribedEvents(): array
    {
        return [
            'postLoad',
            'postPersist',
        ];
    }

    public function postLoad(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getObject();
        if ($entity instanceof TranslatableInterface) {
            $this->entityTranslator->initializeCurrentTranslation($entity);
        }
    }

    public function postPersist(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getObject();
        if ($entity instanceof TranslatableInterface) {
            $this->entityTranslator->initializeCurrentTranslation($entity);
        }
    }
}
