<?php


namespace App\FrontModule\Presenters;


use App\Components\Forms\EventCreateForm;
use App\Components\Forms\Factories\IEventCreateFormFactory;
use App\Model\Entities\Components\Event\Event;
use App\Model\Exceptions\Db\RecordNotFoundException;
use Nette\Http\IResponse;

class EventsPresenter extends FrontBasePresenter
{
    /** @var  Event */
    protected $event;

    /** @var  IEventCreateFormFactory */
    protected $eventCreateFormFactory;

    public function injectForms(IEventCreateFormFactory $eventCreateFormFactory)
    {
        $this->eventCreateFormFactory = $eventCreateFormFactory;
    }

    public function actionDefault()
    {
        if ($this->site->isGlobalSite()) {
            $this->pageHeader = 'My events';
        } else {
            $this->pageHeader = 'Events';
        }
    }

    public function renderDefault()
    {
        if ($this->site->isGlobalSite()) {
            $this->template->events = $this->siteFacade->getEventReader()->findUserEvents($this->user->id);
        } else {
            $this->template->events = $this->siteFacade->getEventReader()->findUpcomingEvents($this->site);
        }

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

    public function actionCreate()
    {
        if ($this->site->isGlobalSite()) {
            $this->redirect('Events:');
        }

        if (!$this->user->isAllowed($this->site, 'create_event')) {
            $this->error(null, IResponse::S403_FORBIDDEN);
        }

        $this->pageHeader = 'Create event';
        $this->breadcrumb->addNode('events', 'Events', 'Events:');
    }

    public function actionView($id)
    {
        try {
            $this->event = $this->siteFacade->getEventReader()->findEventById($id);
        } catch (RecordNotFoundException $e) {
            $this->error('Page not found.');
        }

        if (!$this->user->isAllowed($this->event, 'view')) {
            $this->error(null, IResponse::S403_FORBIDDEN);
        }

        $this->pageHeader = $this->event->getName();
        $this->breadcrumb->addNode('events', 'Events', 'Events:');
    }

    public function renderView()
    {
    	$this->template->event = $this->event;
    }

    public function createComponentEventCreateForm() : EventCreateForm
    {
        $component = $this->eventCreateFormFactory->create($this->site);
        $component->onSave[] = function () {
            $this->redirect('Events:');
        };

        return $component;
    }

    public function handleParticipate()
    {
        if (!$this->user->isAllowed($this->event, 'join')) {
            $this->error(null, IResponse::S403_FORBIDDEN);
        }

        $this->siteFacade->getEventWriter()->participate($this->event);
        $this->redirect('this');
    }

    public function handleCancelParticipation()
    {
        $this->siteFacade->getEventWriter()->cancelParticipation($this->event);
        $this->redirect('this');
    }
}