<?php


namespace App\Components\Forms;


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

class NewsEditForm extends NewsForm
{
    /** @var  News */
    protected $news;

    public function setNews($news)
    {
        $this->news = $this->siteFacade->getNewsReader()->validateNews($news);
    }

    protected function createComponentForm() : BootstrapForm
    {
        $form =  $this->setupForm();
        if ($this->news->getState() == News::CREATED) {
            $form->addSubmit('submitPublish', 'Save and publish')
                ->setButtonDisplay(BootstrapForm::BTN_DISPLAY_INLINE)
                ->setButtonType(BootstrapForm::BTN_TYPE_PRIMARY);
        } else {
            $form->addSubmit('submitSave', 'Save')
                ->setButtonDisplay(BootstrapForm::BTN_DISPLAY_INLINE)
                ->setButtonType(BootstrapForm::BTN_TYPE_SUCCESS);
        }


        $defaults = array();
        $defaults['title'] = $this->news->getTitle();
        $defaults['language'] = $this->news->getLanguage()->getIdentifier();
        $defaults['description'] = $this->news->getDescription();
        $defaults['content'] = $this->news->getContent();
        $form->setDefaults($defaults);

        return $form;
    }

    public function formSucceeded(BootstrapForm $form, $values)
    {
        if ($this->news->getState() == News::CREATED) {
            $publish = $form->getComponent('submitPublish')->isSubmittedBy();
        } else {
            $publish = false;
        }

        try {
            $this->siteFacade->getNewsWriter()->editNews($this->news, $values->language, $values->title, $values->description, $values->content, $publish);
            if ($publish) {
                $this->onPublish($this, $this->news);
            } else {
                $this->onSave($this, $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);
        }
    }
}