<?php

namespace AppBundle\Listener;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\FewoLodgingImage;
use AppBundle\Entity\FewoLodgingGroupImage;
use AppBundle\Service\FileManager;

class DoctrineFileListener
{
    private $uploader;

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

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->deleteFile($entity);
    }

    private function uploadFile($entity)
    {


        if (!$entity instanceof FewoLodgingImage && !$entity instanceof FewoLodgingGroupImage)
        {
            return;
        }

        $file = $entity->getFile();


        // man könnte hier noch anpassungen tätigen, wie zb. dass man den dateinamen selbst über fileName angeben kann
        // oder man nutzt (so wie es jetzt ist) fileName dafür, es als alt-Name usw. zu benutzen und der dateiname bleibt kryptisch


        // only upload new files
        if (!$file instanceof UploadedFile)
        {
            return;
        }

        $fileName = $this->uploader->upload($file);
        $entity->setFile($fileName);
    }

    private function deleteFile($entity)
    {
        if($entity instanceof FewoLodgingImage)
        {
            $this->uploader->delete($entity);
        }

        if($entity instanceof FewoLodgingGroupImage)
        {
            $this->uploader->deleteGroup($entity);
        }

       
    }
}