<?php

namespace App\Repository;

use App\Entity\UserTripLocation;
use App\Entity\UserTrip;
use App\Entity\Location;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class UserTripLocationRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, UserTripLocation::class);
    }

    public function save(UserTripLocation $userTripLocation, bool $flush = false): void
    {
        $this->getEntityManager()->persist($userTripLocation);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    public function remove(UserTripLocation $userTripLocation, bool $flush = false): void
    {
        $this->getEntityManager()->remove($userTripLocation);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    /**
     * @return UserTripLocation[]
     */
    public function findByUserTrip(UserTrip $userTrip): array
    {
        return $this->createQueryBuilder('utl')
            ->andWhere('utl.userTrip = :userTrip')
            ->setParameter('userTrip', $userTrip)
            ->orderBy('utl.plannedDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return UserTripLocation[]
     */
    public function findByLocation(Location $location): array
    {
        return $this->createQueryBuilder('utl')
            ->andWhere('utl.location = :location')
            ->setParameter('location', $location)
            ->orderBy('utl.plannedDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return UserTripLocation[]
     */
    public function findByDateRange(DateTimeImmutable $start, DateTimeImmutable $end): array
    {
        return $this->createQueryBuilder('utl')
            ->andWhere('utl.plannedDate >= :start')
            ->andWhere('utl.plannedDate <= :end')
            ->setParameter('start', $start)
            ->setParameter('end', $end)
            ->orderBy('utl.plannedDate', 'ASC')
            ->getQuery()
            ->getResult();
    }
}