<?php


namespace App\Model\Services;


use App\Model\Entities\Components\Event\Event;
use App\Model\Entities\Security\User;
use App\Model\Entities\Templates\EventTemplate;
use App\Model\Interfaces\ISite;
use DateTime;
use Kdyby\Doctrine\EntityRepository;

class EventService extends BaseService
{
    /** @var  EntityRepository */
    protected $events;

    protected function startup()
    {
        $this->events = $this->getRepository(Event::class);
    }

    public function findEventById(int $id)
    {
        return $this->events->find($id);
    }

    public function findUpcomingEvents(ISite $site)
    {
        $from = new DateTime();
        $to = new DateTime();
        $criteria = ['site' => $site, 'startAt >=' => $from->setTime(0, 0, 0), 'startAt <=' => $to->setTime(0, 0, 0)->modify('+1 month')];

        return $this->events->findBy($criteria, ['startAt' => 'ASC'], 15);
    }

    public function findUserEvents($userEntity)
    {
        $from = new DateTime();
        $to = new DateTime();

        return $this->events->createQueryBuilder('e')
            ->andWhere(':user MEMBER OF e.users')->setParameter('user', $userEntity)
            ->andWhere('e.startAt >= :from')->setParameter('from', $from->setTime(0, 0, 0))
            ->andWhere('e.startAt <= :to')->setParameter('to', $to->setTime(0, 0, 0)->modify('+1 month'))
            ->getQuery()
            ->getResult();
    }

    public function createEvent(User $createdBy, ISite $site, EventTemplate $template, string $name, string $description, DateTime $start, DateTime $end = null, int $limit = null) : Event
    {
        $event = new Event($createdBy);
        $event->setSite($site);
        $event->setTemplate($template);
        $event->setName($name);
        $event->setDescription($description);
        $event->setStartAt($start);
        $event->setEndAt($end);
        $event->setUserLimit($limit);

        $this->persist($event);
        return $event;
    }
}