<?php


namespace App\Components\Forms;


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

class NewForumPostForm extends PostForm
{
    /** @var  Topic */
    protected $topic;

    public function setTopic($topic)
    {
        $this->topic = $this->siteFacade->getForumReader()->validateTopic($topic);
    }

    protected function createComponentForm() : BootstrapForm
    {
        $form = $this->setupForm();
        $form->addSubmit('submit', 'Submit');

        return $form;
    }

    /**
     * @param BootstrapForm $form
     * @param $values
     * @throws AbortException
     */
    public function formSucceeded(BootstrapForm $form, $values)
    {
        try {
            $post = $this->siteFacade->getForumWriter()->createPost($this->topic, $values->title, $values->message);
            $this->onSave($this, $post);
        } catch (AbortException $e) {
            throw $e;       // redirect;
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->presenter->flashMessage('Record saving has failed.', FlashMessage::ERROR);
            $this->onError($this);
        }
    }
}