<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


use AutoAdmin\Bundle\Content\Context\SiteContext;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Model\LocalizedInterface;
use AutoAdmin\Bundle\Content\Model\SiteInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use RuntimeException;

class SiteContextSubscriber implements EventSubscriber
{
    private SiteContext $siteContext;

    public function __construct(SiteContext $siteContext)
    {
        $this->siteContext = $siteContext;
    }

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

    public function prePersist(LifecycleEventArgs $args): void
    {
        $this->linkSite($args);
        $this->linkLocale($args);
    }

    public function linkSite(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();

        if ($entity instanceof SiteInterface && empty($entity->getSite())) {
            if (null !== $site = $this->siteContext->getSite()) {
                $em = $args->getObjectManager();
                $entity->setSite($em->getRepository(Site::class)->find($site->getId()));
            } else {
                throw new RuntimeException('Could not identify current site in context. Aborting.');
            }
        }
    }

    private function linkLocale(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof LocalizedInterface && empty($entity->getLocale())) {
            if (null !== $locale = $this->siteContext->getLocale()) {
                $em = $args->getObjectManager();
                $entity->setLocale($em->getRepository(Locale::class)->find($locale->getId()));
            } else {
                throw new RuntimeException('Could not identify current site in context. Aborting.');
            }
        }
    }
}
