<?php

namespace App\Repository;

use App\Entity\ReviewSource;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\ORMException;
use Doctrine\Persistence\ManagerRegistry;

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

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function add(ReviewSource $entity, bool $flush = true): void
    {
        if (! $entity->getDateCreate()) {
            $entity->setDateCreate(new \DateTime());
        }

        $this->_em->persist($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    /**
     * @throws ORMException
     * @throws OptimisticLockException
     */
    public function remove(ReviewSource $entity, bool $flush = true): void
    {
        $this->_em->remove($entity);
        if ($flush) {
            $this->_em->flush();
        }
    }

    public function findByCity($cityId)
    {
        return $this->createQueryBuilder('r')
            ->select('r.name, SUM(r.countRow) AS count_row_total, (SUM(r.rating) / COUNT(r.id)) AS rating_total')
            ->distinct()
            ->where('r.city in (:city)')
            ->setParameter('city', $cityId)
            ->groupBy('r.name')
            ->getQuery()
            ->getResult()
        ;
    }

}
