<?php


namespace App\Components\Forms;


use App\Model\Enums\FlashMessage;
use App\Model\Facades\SiteFacade;
use App\Model\Translator;
use Doctrine\ORM\EntityManager;
use Nette\Application\AbortException;
use Throwable;
use Tracy\Debugger;
use xhulav\BootstrapForms\Rendering\BootstrapHorizontalFormRenderer;

class NavItemGalleryForm extends NavItemForm
{
    /** @var EntityManager */
    protected $entityManager;

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


    /**
     * @return BootstrapForm
     */
    protected function createComponentForm() : BootstrapForm
    {
        $form = $this->setupForm();
        $form->addTextArea('description', 'Description');
        $form->addSubmit('submit', 'Submit')->setButtonType(BootstrapForm::BTN_TYPE_PRIMARY);

        $form->getComponent('icon')->setDefaultValue('picture-o');

        $form->setRenderer(new BootstrapHorizontalFormRenderer());
        return $form;
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        try {
            $this->entityManager->beginTransaction();
            $gallery = $this->siteFacade->getGalleryWriter()->createGallery($values->template, $values->title, $values->description, true);
            $navItem = $this->siteFacade->getNavigationWriter()->attachGallery($this->site, $gallery, $values->navTitle, $values->icon);
            $this->entityManager->commit();
            $this->onSave($this, $navItem);
        } catch (AbortException $e){
            throw $e;     // redirect
        } catch (Throwable $e) {
            $this->entityManager->rollback();
            Debugger::log($e);
            $this->presenter->flashMessage('Record saving has failed.', FlashMessage::ERROR);
            $this->onError($this);
        }
    }

    protected function getTemplates() : array
    {
        return $this->siteFacade->getTemplateReader()->getGallerySelectBoxPairs($this->site);
    }
}