<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Behavior\HasFile;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\Uploader\FileUploader;
use CpCreation\VitiCore\Media\Model\File;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class FileSubscriber implements EventSubscriber
{

    /**
     * @var FileUploader
     */
    private $uploader;


    public function __construct(FileUploader $uploader)
    {
        $this->uploader = $uploader;
    }

    public function getSubscribedEvents()
    {

        return [
            Events::prePersist,
            Events::postUpdate,
        ];
    }

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function prePersist(LifecycleEventArgs $args)
    {

        $entity = $args->getEntity();
        if ($entity instanceof File) {
            if ($entity->getFile()) {
                /** @var File $file */
                $file = $this->uploader->upload($entity->getFile());
                $entity->setPath($file->getPath());
                $entity->setSize($file->getSize());
                $entity->setMimeType($file->getMimeType());
                $entity->setOriginalName($file->getOriginalName());
            }
        }
    }


    /**
     * @param LifecycleEventArgs $args
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     * @throws \Exception
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof HasFile && $entity->getFile()) {

            if ($entity->getFile()->getFile()) {
                /** @var File $file */
                $file          = $this->uploader->upload($entity->getFile()->getFile());
                $entityManager = $args->getEntityManager();
                $entityManager->remove($entity->getFile());
                $entity->setFile($file);
                $entityManager->persist($entity);
                $entityManager->flush();
            }
        }
    }
}
