<?php


namespace App\Components\Forms;


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

class NewsCreateForm extends NewsForm
{
    /** @var  NewsContainer */
    protected $container;

    public function setNewsContainer($container)
    {
        $this->container = $this->siteFacade->getNewsReader()->validateContainer($container);
    }

    /**
     * @return BootstrapForm
     */
    protected function createComponentForm() : BootstrapForm
    {
        $form = $this->setupForm();
//        $form->addSubmit('submitSave', 'Save')
//            ->setButtonDisplay(BootstrapForm::BTN_DISPLAY_INLINE)
//            ->setButtonType(BootstrapForm::BTN_TYPE_SUCCESS);
        $form->addSubmit('submitPublish', 'Save and publish')
            ->setButtonDisplay(BootstrapForm::BTN_DISPLAY_INLINE)
            ->setButtonType(BootstrapForm::BTN_TYPE_PRIMARY);

        return $form;
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        $publish = $form->getComponent('submitPublish')->isSubmittedBy();

        try {
            $news = $this->siteFacade->getNewsWriter()->createNews($this->container, $values->language, $values->title, $values->description, $values->content, $publish);
            if ($publish) {
                $this->onPublish($this, $news);
            } else {
                $this->onSave($this, $news);
            }
        } catch (AbortException $e) {
            throw $e;   // redirect
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->presenter->flashMessage('Record saving has failed.', FlashMessage::ERROR);
            $this->onError($this);
        }
    }
}