<?php

namespace AppBundle\Entity;

/**
 * FlightPeriodRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FlightPeriodRepository extends \Doctrine\ORM\EntityRepository
{
    public function getIndexedFlightPeriodsForTimePeriod($startDate, $endDate, $arrivalPointIds = null)
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb
            ->from('AppBundle:FlightPeriod', 'fp')
            ->addSelect('fp')
            ->leftJoin('fp.departures', 'fp_dep')
            ->addSelect('fp_dep')
            ;

        if ($startDate !== null)
        {
            $qb->where('fp.startDate >= :startDate');
            $qb->setParameter('startDate', $startDate);
        }
        if ($endDate !== null)
        {
            $qb->andWhere('fp.endDate <= :endDate');
            $qb->setParameter('endDate', $endDate);
        }
        if (!empty($arrivalPointIds))
        {
            if (is_array($arrivalPointIds))
            {
                $qb->andWhere($qb->expr()->in('IDENTITY(fp.travelArrivalPoint)', $arrivalPointIds));
            }
            else
            {
                $qb->andWhere($qb->expr()->eq('IDENTITY(fp.travelArrivalPoint)', $arrivalPointIds));
            }
        }

        $unindexedFlightPeriods = $qb->getQuery()->getResult();
        $ret = [];

        // Index by CONCAT(start date, end date, arrival point id):
        /** @var FlightPeriod $flightPeriod */
        foreach ($unindexedFlightPeriods as $flightPeriod)
        {
            $ret[$flightPeriod->getStartDate()->format('Y-m-d') .
            $flightPeriod->getEndDate()->format('Y-m-d') .
            $flightPeriod->getTravelArrivalPoint()->getId()] = $flightPeriod;
        }

        return $ret;
    }
}
