<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


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 AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Events;
use RuntimeException;

class SiteContextSubscriber implements EventSubscriber
{

    public function __construct(
        private SiteContextHelper $contextHelper
    ) {
    }

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

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

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

        if ($entity instanceof SiteInterface && empty($entity->getSite())) {
            if (null !== $site = $this->contextHelper->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(PrePersistEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof LocalizedInterface && empty($entity->getLocale())) {
            if (null !== $locale = $this->contextHelper->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.');
            }
        }
    }
}
