<?php


namespace App\Components\Forms;


use App\Model\Entities\Components\Forum\Forum;
use App\Model\Enums\FlashMessage;
use Nette\Application\AbortException;
use Throwable;
use Tracy\Debugger;

class ForumCreateForm extends ForumForm
{
    /** @var  Forum */
    protected $parentForum;

    public function setParentForum($forum)
    {
        $this->parentForum = $this->siteFacade->getForumReader()->validateForum($forum);
    }

    /**
     * @return BootstrapForm
     */
    protected function createComponentForm() : BootstrapForm
    {
        // ForumTemplate is always attached to site => getter will work here
        $site = $this->parentForum->getResourceTemplate()->getSite();

        $form = $this->setupForm();
        $form->addSelect('template', 'Access rights', $this->siteFacade->getTemplateReader()->getForumSelectBoxPairs($site))->setPrompt('Use parent forum access rights');
        $form->addSubmit('submit', 'Create');

        return $form;
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        try {
            $forum = $this->siteFacade->getForumWriter()->createForum($values->name, $values->description, $values->template, $this->parentForum, true);
            $this->onSave($this, $forum);
        } catch (AbortException $e) {
            throw $e;       // redirect
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->presenter->flashMessage('Record saving has failed.', FlashMessage::ERROR);
            $this->onError($this);
        }
    }
}