<?php

namespace App\Repository;

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

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

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

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

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

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

    /**
     * @return Trip[]
     */
    public function findByVessel(Vessel $vessel): array
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.vessel = :vessel')
            ->setParameter('vessel', $vessel)
            ->orderBy('t.startDate', 'DESC')
            ->getQuery()
            ->getResult();
    }

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

    public function findByPilotReference(string $pilotReference): ?Trip
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.pilotReference = :pilotReference')
            ->setParameter('pilotReference', $pilotReference)
            ->getQuery()
            ->getOneOrNullResult();
    }
}