<?php

namespace App\Repository;

use App\Entity\Vessel;
use App\Entity\ShippingCompany;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

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

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

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

    /**
     * @return Vessel[]
     */
    public function findByCompany(ShippingCompany $company): array
    {
        return $this->createQueryBuilder('v')
            ->andWhere('v.company = :company')
            ->setParameter('company', $company)
            ->orderBy('v.name', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findOneByNameAndCompany(string $name, ShippingCompany $company): ?Vessel
    {
        return $this->createQueryBuilder('v')
            ->andWhere('v.name = :name')
            ->andWhere('v.company = :company')
            ->setParameter('name', $name)
            ->setParameter('company', $company)
            ->getQuery()
            ->getOneOrNullResult();
    }
}