<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\Components\Event\Event;
use App\Model\Facades\Readers\EventReader;
use App\Model\Facades\Readers\SiteReader;
use App\Model\Facades\Readers\TemplateReader;
use App\Model\Services\EventService;
use DateTime;
use Throwable;

class EventWriter extends BaseWriter
{
    /** @var  EventService */
    protected $eventService;
    /** @var  SiteReader */
    protected $siteReader;
    /** @var  TemplateReader */
    protected $templateReader;
    /** @var  EventReader */
    protected $eventReader;

    public function inject(EventService $eventService, SiteReader $siteReader, TemplateReader $templateReader, EventReader $eventReader)
    {
        $this->eventService = $eventService;
        $this->siteReader = $siteReader;
        $this->templateReader = $templateReader;
        $this->eventReader = $eventReader;
    }

    public function createEvent($site, $template, string $name, string $description, DateTime $start, $end = null, $limit = null) : Event
    {
        $siteEntity = $this->siteReader->validateSite($site);
        $templateEntity = $this->templateReader->validateEventTemplate($template);

        if (empty($end)) {
            $end = null;
        }
        if (empty($limit)) {
            $limit = null;
        }

        try {
            $this->beginTransaction();
            $event = $this->eventService->createEvent($this->getLoggedInUser(), $siteEntity, $templateEntity, $name, $description, $start, $end, $limit);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw  $e;
        }

        return $event;
    }

    public function participate($event)
    {
        $eventEntity = $this->eventReader->validateEvent($event);

        try {
            $this->beginTransaction();
            $eventEntity->addUser($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }

    public function cancelParticipation($event)
    {
        $eventEntity = $this->eventReader->validateEvent($event);

        try {
            $this->beginTransaction();
            $eventEntity->removeUser($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }
}