<?php


namespace App\FrontModule\Presenters;


use App\Components\Forms\Factories\IGalleryImageUploadFormFactory;
use App\Components\Forms\GalleryImageUploadForm;
use App\Model\Entities\Components\Gallery\Gallery;
use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Uploader;
use Nette\Http\IResponse;

class GalleryPresenter extends FrontBasePresenter
{
    /** @var  Uploader */
    protected $uploader;
    /** @var  Gallery */
    protected $gallery;
    /** @var  IGalleryImageUploadFormFactory */
    protected $galleryImageUploadFormFactory;

    public function inject(Uploader $uploader)
    {
        $this->uploader = $uploader;
    }

    public function injectForms(IGalleryImageUploadFormFactory $galleryImageUploadFormFactory)
    {
        $this->galleryImageUploadFormFactory = $galleryImageUploadFormFactory;
    }

    public function actionView($id)
    {
        try {
            $this->gallery = $this->siteFacade->getGalleryReader()->findGalleryById($id);
        } catch (RecordNotFoundException $e) {
            $this->error('Page not found.');
        }

        if (!$this->user->isAllowed($this->gallery, 'view')) {
            $this->error(null, IResponse::S403_FORBIDDEN);
        }

        $this->pageHeader = $this->gallery->getName();
    }

    public function renderView()
    {
        $this->template->gallery = $this->gallery;
        $this->template->images = $this->gallery->getImages();
    }

    protected function createComponentFileUpload() : GalleryImageUploadForm
    {
        $component = $this->galleryImageUploadFormFactory->create($this->gallery);
        $component->onSave[] = function () {
            $this->redirect('this');
        };

        return $component;
    }
}