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

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Manager\CarrierProviderManager;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Service\Uploader\FileUploader;
use CpCreation\VitiCore\Shop\Model\ShippingConfig;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use League\Flysystem\Filesystem;

class ShippingConfigSubscriber implements EventSubscriber
{
    /**
     * @var CarrierProviderManager
     */
    private $manager;

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

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

    public function getSubscribedEvents()
    {

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

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFileSup()) {
                $file = $this->uploader->upload($entity->getFileSup()->getFile());
                $entity->setFileSup($file);
            }
        }
    }

    /**
     * @param LifecycleEventArgs $event
     * @throws \Exception
     */
    public function postPersist(LifecycleEventArgs $event)
    {
        $entity = $event->getObject();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFile() || $entity->getFileSup()) {
                $this->manager->createProviderManager($entity);
            }
        }
    }

    /**
     * @param LifecycleEventArgs $event
     * @throws \Exception
     */
    public function postUpdate(LifecycleEventArgs $event)
    {
        $entity = $event->getObject();
        if ($entity instanceof ShippingConfig) {
            if ($entity->getFileSup()) {
                if ($entity->getFileSup()->getFile()) {
                    $entityManager = $event->getEntityManager();
                    $entityManager->remove($entity->getFileSup());
                    $file = $this->uploader->upload($entity->getFileSup()->getFile());
                    $entity->setFileSup($file);
                    $entityManager->persist($entity);
                    $entityManager->flush();
                }
            }
            if ($entity->getFile() || $entity->getFileSup()) {
                $this->manager->createProviderManager($entity);
            }
        }
    }

}