<?php


namespace App\Components\Forms;


use App\Model\Entities\Game;
use App\Model\Enums\FlashMessage;
use App\Model\Facades\GameFacade;
use App\Model\Facades\SiteFacade;
use App\Model\Translator;
use NasExt\Forms\Controls\DependentSelectBoxData;
use Nette\Application\AbortException;
use Throwable;
use Tracy\Debugger;
use xhulav\BootstrapForms\Rendering\BootstrapHorizontalFormRenderer;

class GuildCreateForm extends GuildForm
{
    /** @var  Game */
    protected $game;
    /** @var GameFacade */
    protected $gameFacade;

    public function __construct(Translator $translator, SiteFacade $siteFacade, GameFacade $gameFacade)
    {
        parent::__construct($translator, $siteFacade);
        $this->gameFacade = $gameFacade;
    }


    public function setGame($game)
    {
        $this->game = $this->siteFacade->getSiteReader()->validateSite($game);
    }

    /**
     * @return BootstrapForm
     */
    protected function createComponentForm() : BootstrapForm
    {
        $form = $this->setupForm();
        $form->addSelect('region', $this->translator->translate('Region'), $this->gameFacade->getRegionReader()->getSelectBoxData($this->game))
            ->setPrompt($this->translator->translate('Select region.'))
            ->setRequired()
            ->setTranslator(null);
        $form->addDependentSelectBox('server', $this->translator->translate('Server'), [$form['region']], [$this, 'fetchServers'])
            ->setRequired()
            ->setAttribute('class', 'select2')
            ->setTranslator(null);
        $form->addSelect('faction', $this->translator->translate('Faction'), $this->gameFacade->getFactionReader()->getSelectBoxPairs($this->game))
            ->setTranslator(null);
        $form->addSubmit('submit', 'Create')->setButtonType(BootstrapForm::BTN_TYPE_PRIMARY);

        $form->setRenderer(new BootstrapHorizontalFormRenderer());

        return $form;
    }

    /**
     * @param BootstrapForm $form
     * @param $values
     * @throws AbortException
     */
    public function formSucceeded(BootstrapForm $form, $values)
    {
        try {
            $guild = $this->siteFacade->getSiteWriter()->createGuild($values->name, $this->game, $values->server, $values->faction);
            $this->onSave($this, $guild);
        } catch (AbortException $e){
            throw $e;       // redirect
        } catch (Throwable $e) {
            Debugger::log($e);
            $this->presenter->flashMessage('Record saving has failed.', FlashMessage::ERROR);
            $this->onError($this);
        }
    }


    public function fetchServers($values)
    {
        $data = new DependentSelectBoxData();
        if ($values['region']) {
            $data->setItems($this->gameFacade->getServerReader()->getSelectBoxPairs($values['region']));
        }

        return $data;
    }
}