<?php


namespace AutoAdmin\Bundle\Content\Doctrine\EventListener;


use AutoAdmin\Bundle\Content\Model\CreatedAtInterface;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Content\Model\UpdatedAtInterface;
use DateTime;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;

class CreateUpdateSubscriber implements EventSubscriber
{
    public function getSubscribedEvents(): array
    {
        return array(
            Events::preUpdate,
            Events::prePersist,
            Events::onFlush,
        );
    }

    public function preUpdate(LifecycleEventArgs $args): void
    {
        $this->updatedAt($args);
    }

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

        if ($entity instanceof UpdatedAtInterface) {
            $datetime = new DateTime();
            $entity->setUpdatedAt($datetime);
        }
    }

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

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

        if ($entity instanceof CreatedAtInterface && !$entity->getCreatedAt()) {
            $datetime = new DateTime();
            $entity->setCreatedAt($datetime);
        }
    }

    public function onFlush(OnFlushEventArgs $args)
    {
        $em = $args->getObjectManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityUpdates() as $entity) {
            // if the $entity implements UpdatedAtInterface and has a translatable "parent" class,
            // do update its "updatedAt" field, $entity will be properly handled in preUpdate method
            if (
                $entity instanceof UpdatedAtInterface
                && $entity instanceof TranslationInterface
                && ($translatable = $entity->getTranslatable())
                && $translatable instanceof UpdatedAtInterface
            ) {
                $translatableClass = get_class($translatable);
                $meta = $em->getClassMetadata($translatableClass);
                $translatable->setUpdatedAt(new DateTime());
                if ($uow->getEntityChangeSet($translatable)) {
                    // the entity has pending changes, we need to recompute/merge
                    $uow->recomputeSingleEntityChangeSet($meta, $translatable);
                } else {
                    // there are no changes, we compute from scratch
                    $uow->computeChangeSet($meta, $translatable);
                }
            }
        }
    }
}
