<?php
namespace Edeclic\HistoryBundle\Utils\EventListener;

use AppBundle\Entity\Company;
use AppBundle\Entity\Note;
use AppBundle\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\EventSubscriber;
use Doctrine\MongoDB\Collection;
use Doctrine\ORM\Event\LifecycleEventArgs;

class EntityHistorySubscriber implements EventSubscriber
{
    private $historyRecordService;
    private $security;
    private $logger;

    public function __construct($historyRecordService, $security, $logger)
    {
        $this->historyRecordService = $historyRecordService;
        $this->security = $security;
        $this->logger = $logger;
    }

    public function getSubscribedEvents()
    {
        return array(
            'postPersist',
            'postUpdate',
            //'postRemove',
            'preRemove',
        );
    }

    //when CREATED
    public function postPersist(LifecycleEventArgs $args)
    {
        $this->AddHistory($args, "c");
    }

    //when UPDATED
    public function postUpdate(LifecycleEventArgs $args)
    {
        $this->AddHistory($args, "u");
    }

    //Before REMOVED
    public function preRemove(LifecycleEventArgs $args)
    {
        $this->AddHistory($args, "d");
    }

    /**
     * @param LifecycleEventArgs $args
     * @param $action
     */
    public function AddHistory(LifecycleEventArgs $args, $action)
    {
        $entity = $args->getEntity();
        if (!$entity instanceof User) {
            $em = $args->getEntityManager();
            if(!is_null($this->security->getToken())){
                $user = $this->security->getToken()->getUser();
                if ($user instanceof User) {
                    $user = $user->getId();
                }
            } else {
                $user = "console";
            }
            $changeSet = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($entity);
            unset($changeSet['utime']);
            $this->historyRecordService->recordIt($user, $action, $em->getClassMetadata(get_class($entity))->getName(), $entity->getId(), serialize($changeSet));
        }
    }
}