<?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 TopicCreateForm extends TopicForm
{
    /** @var  Forum */
    protected $forum;

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

    /**
     * @return BootstrapForm
     */
    protected function createComponentForm() : BootstrapForm
    {
        $form = $this->setupForm();
        $form->addSubmit('submit', 'Create');

        return $form;
    }

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