<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


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

class TranslationCreationListener implements EventSubscriber
{
    private EntityTranslator $translator;
    private ContentFactory $contentFactory;

    public function __construct(EntityTranslator $translator, ContentFactory $contentFactory)
    {
        $this->translator = $translator;
        $this->contentFactory = $contentFactory;
    }

    public function getSubscribedEvents(): array
    {
        return [
            Events::prePersist,
        ];
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof TranslatableInterface) {
            if ($entity->getId() === null) {
                $current = $entity->getCurrentTranslation();
                if (null === $current) {
                    $entity = $this->contentFactory->createTranslationForEntity($entity);
                }
            }

        }
    }
}