<?php

namespace App\Repository;

use App\Entity\TripLocation;
use App\Entity\Trip;
use App\Entity\Location;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

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

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

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

    /**
     * @return TripLocation[]
     */
    public function findByTrip(Trip $trip): array
    {
        return $this->createQueryBuilder('tl')
            ->andWhere('tl.trip = :trip')
            ->setParameter('trip', $trip)
            ->orderBy('tl.date', 'ASC')
            ->getQuery()
            ->getResult();
    }

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

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