<?php

declare(strict_types=1);

namespace App\CoreModule\Presenters;

use App\CoreModule\Model\InvitationManager;
use App\CoreModule\Model\EventManager;
use App\Presenters\BasePresenter;
use Nette\Application\AbortException;
use Nette\Application\BadRequestException;
use Nette\Application\UI\Form;
use Nette\Database\UniqueConstraintViolationException;
use Nette\Utils\ArrayHash;

class InvitationPresenter extends BasePresenter {

	public $invitationManager;
	
	public function __construct(InvitationManager $invitationManager) {
		parent::__construct();

		$this->invitationManager = $invitationManager;
	}

	public function renderDefault($url = null) {

		if (!($invitation = $this->invitationManager->getInvitation($url)))
			$this->error(); 

		$this->template->invitation = $invitation;

		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;

	}

	public function renderList() {
		$this->template->invitations = $this->invitationManager->getInvitations();

		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;

	}

	public function renderEditor() {	
		if ($this->user->isLoggedIn()) $this->template->username = $this->user->identity->name;

		$this->template->invitationManager = $this->invitationManager;
	}

	public function actionRemove($url = null) {
		$this->invitationManager->removeInvitation($url);
		$this->flashMessage('Pozvánka byla úspěšně odstraněna.');
		$this->redirect('Invitation:list');
	}

	public function actionEditor($url) {

		if (is_numeric($url)) {

			if (!($invitation = $this->invitationManager->getInvitation($url))) 
				$this->flashMessage('Pozvánka nebyla nalezena.'); 
			else $this['editorForm']->setDefaults($invitation); 

		} else {

			if (!($invitation = $this->invitationManager->getInvitationKey($url))) 
				$this->flashMessage('Pozvánka nebyla nalezena.'); 
			else $this['editorForm']->setDefaults($invitation); 
		}

	}

	protected function createComponentEditorForm() {
		$form = $this->formFactory->create();
		$form->addHidden('invitation_id');
		$form->addText('name', 'Název:')->setRequired()->setHtmlAttribute('class','form-control form');
		$form->addTextArea('body')->setHtmlAttribute('class','form-control form');
		$form->addHidden('created_at');
		$form->addSubmit('save', 'Uložit pozvánku')->setHtmlAttribute('class','btn btn-secondary form-btn-b');
		$form->onSuccess[] = [$this, "editorFormSucceeded"];

		return $form;
	}

	public function editorFormSucceeded(Form $form, ArrayHash $values) {
		try {
			$event_url = $this->getParameter('url');

			$this->invitationManager->provedZapis($form, $event_url, $values);

			$this->flashMessage('Pozvánka byla úspěšně uložena.');
			$this->redirect('Invitation:list');
		} catch (UniqueConstraintViolationException $e) {
				$this->flashMessage('Pozvánka již existuje.');
		}
	}

}
