<?php


namespace App\Components\Forms;


use App\Model\Crates\UploaderNode;
use App\Model\Entities\Components\Gallery\Gallery;
use App\Model\Exceptions\Uploader\ImageCacheExpiredException;
use App\Model\Facades\SiteFacade;
use App\Model\Translator;
use App\Model\Uploader;
use Kdyby\Doctrine\EntityManager;
use Nette\Application\AbortException;
use Throwable;
use Tracy\Debugger;

class GalleryImageUploadForm extends JQueryUploaderForm
{
    /** @var EntityManager */
    protected $entityManager;
    /** @var SiteFacade */
    protected $siteFacade;
    /** @var  Gallery */
    protected $gallery;

    public function __construct(Translator $translator, Uploader $uploader, EntityManager $entityManager, SiteFacade $siteFacade)
    {
        parent::__construct($translator, $uploader);
        $this->entityManager = $entityManager;
        $this->siteFacade = $siteFacade;
    }

    public function setGallery($gallery)
    {
        $this->gallery = $this->siteFacade->getGalleryReader()->validateGallery($gallery);
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        /** @var UploaderNode[] $nodes */
        $nodes = $values->uploader;

        $savedImages = array();
        try {
            $this->entityManager->beginTransaction();
            foreach ($nodes as $node) {
                $imageFileName = $this->uploader->saveFileFromCache($node->getCacheKey(), Uploader::GALLERY);
                $image = $this->siteFacade->getImageWriter()->createImage($node->getFileName(), $imageFileName);
                $this->siteFacade->getGalleryWriter()->attachImage($this->gallery, $image);
                $savedImages[] = $imageFileName;
            }
            $this->entityManager->commit();
            $this->onSave($this);
        } catch (AbortException $e) {
            throw $e;     // redirect
        } catch (ImageCacheExpiredException $e) {
            $this->entityManager->rollback();
            foreach ($savedImages as $image) {
                $this->uploader->deleteImage($image);
            }
            $this->presenter->flashMessage('Form has expired.');
            $this->onError($this);
        } catch (Throwable $e) {
            $this->entityManager->rollback();
            Debugger::log($e);
            foreach ($savedImages as $image) {
                $this->uploader->deleteImage($image);
            }
            $this->presenter->flashMessage('File upload failed.');
            $this->onError($this);
        }
    }
}