<?php

namespace App\Repository;

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

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

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

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

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

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

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

    /**
     * @return UserTripWorkLog[]
     */
    public function findByStartLocation(Location $location): array
    {
        return $this->createQueryBuilder('wl')
            ->andWhere('wl.startLocation = :location')
            ->setParameter('location', $location)
            ->orderBy('wl.startDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

    /**
     * @return UserTripWorkLog[]
     */
    public function findByEndLocation(Location $location): array
    {
        return $this->createQueryBuilder('wl')
            ->andWhere('wl.endLocation = :location')
            ->setParameter('location', $location)
            ->orderBy('wl.startDate', 'ASC')
            ->getQuery()
            ->getResult();
    }

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