<?php
namespace App\Listener;

use App\Entity\Flux;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use Symfony\Component\Security\Core\Security;

class FluxListener implements EventSubscriber
{
    private $em;
    private $security;

    public function __construct(EntityManagerInterface $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    public function getSubscribedEvents()
    {
        return array(Events::onFlush);
    }

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

        $inserted = $uow->getScheduledEntityInsertions();

        foreach ($inserted as $entity) {
            if ($entity instanceof Flux) {
                $topersists = $entity->operate($em);
                foreach ($topersists as $topersist) {
                    $class = $em->getClassMetadata(get_class($topersist));
                    $em->persist($topersist);
                    $em->getUnitOfWork()->computeChangeSet($class, $topersist);
                }
                // @TODO : do something (log, save somewhere else...) on flux persist
                //      => @tag sur un service ?
            }
        }
    }
}
