<?php

namespace App\Repository;

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

/**
 * @extends ServiceEntityRepository<FoundObject>
 *
 * @method FoundObject|null find($id, $lockMode = null, $lockVersion = null)
 * @method FoundObject|null findOneBy(array $criteria, array $orderBy = null)
 * @method FoundObject[]    findAll()
 * @method FoundObject[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class FoundObjectRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, FoundObject::class);
    }

    public function countByProviderAndYear(int $providerId, int $year): int
    {
        $start = new \DateTimeImmutable(sprintf('%d-01-01 00:00:00', $year));
        $end = $start->modify('+1 year');

        return (int) $this->createQueryBuilder('fo')
            ->select('COUNT(fo.id)')
            ->andWhere('IDENTITY(fo.locationProvider) = :providerId')
            ->andWhere('fo.createdAt >= :start')
            ->andWhere('fo.createdAt < :end')
            ->setParameter('providerId', $providerId)
            ->setParameter('start', $start)
            ->setParameter('end', $end)
            ->getQuery()
            ->getSingleScalarResult();
    }

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

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

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

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

//    /**
//     * @return FoundObject[] Returns an array of FoundObject objects
//     */
//    public function findByExampleField($value): array
//    {
//        return $this->createQueryBuilder('f')
//            ->andWhere('f.exampleField = :val')
//            ->setParameter('val', $value)
//            ->orderBy('f.id', 'ASC')
//            ->setMaxResults(10)
//            ->getQuery()
//            ->getResult()
//        ;
//    }

//    public function findOneBySomeField($value): ?FoundObject
//    {
//        return $this->createQueryBuilder('f')
//            ->andWhere('f.exampleField = :val')
//            ->setParameter('val', $value)
//            ->getQuery()
//            ->getOneOrNullResult()
//        ;
//    }
}