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

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\Uploader\ImageUploader;
use CpCreation\VitiCore\Product\Model\Product;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

class ProductSubscriber implements EventSubscriber
{
    private $uploader;

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

    public function getSubscribedEvents()
    {

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

    /**
     * @param LifecycleEventArgs $args
     */
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Product) {
            if ($entity->getSecondImage()) {
                if ($entity->getSecondImage()->getFile()) {
                    $file = $this->uploader->upload($entity->getSecondImage()->getFile());
                    $entity->setSecondImage($file);
                }
            }

            $entity->setPositionShop($entity->getPosition());
        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Product) {

            $entity->setPositionShop($entity->getPosition());
            $args->getEntityManager()->persist($entity);
            $args->getEntityManager()->flush();
        }
    }


    /**
     * @param LifecycleEventArgs $args
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Product) {
            if ($entity->getSecondImage()) {
                if ($entity->getSecondImage()->getFile()) {
                    $file = $this->uploader->upload($entity->getSecondImage()->getFile());
                    $entityManager = $args->getEntityManager();
                    $entityManager->remove($entity->getSecondImage());
                    $entity->setSecondImage($file);
                    $entityManager->persist($entity);
                    $entityManager->flush();
                }
            }
        }
    }
}
