<?php

namespace App\Repository;

use App\Entity\Location;
use App\Entity\Zone;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

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

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

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

    /**
     * @return Location[]
     */
    public function findByZone(Zone $zone): array
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.zone = :zone')
            ->setParameter('zone', $zone)
            ->orderBy('l.name', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findOneByNameAndZone(string $name, Zone $zone): ?Location
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.name = :name')
            ->andWhere('l.zone = :zone')
            ->setParameter('name', $name)
            ->setParameter('zone', $zone)
            ->getQuery()
            ->getOneOrNullResult();
    }
}