<?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\PrePersistEventArgs;
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(PrePersistEventArgs $args): void
    {
        $entity = $args->getObject();

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

        }
    }
}
