<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


use AutoAdmin\Bundle\Content\Model\NameInterface;
use AutoAdmin\Bundle\Content\Model\SlugInterface;
use AutoAdmin\Bundle\Content\Model\TitleInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Core\Doctrine\Traits\ListenerStateManagerTrait;
use AutoAdmin\Bundle\Core\Slugger\Slugger;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;

class SlugSubscriber implements EventSubscriber
{
    use ListenerStateManagerTrait;

    private Slugger $slugger;

    public function __construct(Slugger $slugger)
    {
        $this->slugger = $slugger;
    }

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

    public function prePersist(PrePersistEventArgs $args): void
    {
        if (!$this->canRun()) {
            return;
        }

        $this->generateSlug($args->getObject());
    }

    public function preUpdate(PreUpdateEventArgs $args): void
    {
        if (!$this->canRun()) {
            return;
        }

        $this->generateSlug($args->getObject());
    }

    public function generateSlug(object $entity): void
    {
        if (
            $entity instanceof SlugInterface
            && (
                // empty slug save
                empty($entity->getSlug())
                // first entity save, even if not empty slug
                || (empty($entity->getId()) && !empty($entity->getSlug()))
            )
        ) {
            $slugInput = null;
            if ($entity instanceof NameInterface) {
                $slugInput = $entity->getName();
            } elseif ($entity instanceof TitleInterface) {
                $slugInput = $entity->getTitle();
            }

            if (null !== $slugInput) {
                $entity->setSlug($this->slugger->slugify($slugInput));
            }
        }

        // generate translation slug for translatable at the same time
        if ($entity instanceof TranslatableInterface) {
            $trans = $entity->getCurrentTranslation();
            $this->generateSlug($trans);
        }
    }
}
