<?php

namespace App\Repository\Prospect\Problem;

use App\Entity\Prospect\Problem;
use App\Service\Prospect\ProblemRepositoryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Symfony\Bridge\Doctrine\RegistryInterface;

final class DoctrineProblemRepository extends ServiceEntityRepository implements ProblemRepositoryInterface
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Problem::class);
    }

    public function findById(int $id): ?Problem
    {
        return $this->findOneBy(['id' => $id]);
    }

    /**
     * @param Problem $problem
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function save(Problem $problem): void
    {
        $this->_em->persist($problem);
        $this->_em->flush();
    }

    /**
     * @param Problem $problem
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(Problem $problem): void
    {
        $this->_em->remove($problem);
        $this->_em->flush();
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $result = $this->queryByGrid($criteria, $orderBy, $limit, $offset);

        return $result->toArray();
    }

    public function count(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $result = $this->queryByGrid($criteria);

        return $result->count();
    }

    /**
     * @param array|null $orderBy
     * @param int|null $limit
     * @param int|null $offset
     */
    private function queryByGrid(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): Collection
    {
        $newCriteria = Criteria::create()
            ->setFirstResult($offset)
            ->setMaxResults($limit);

        if ($orderBy) {
            $newCriteria->orderBy($orderBy);
        }

        if (array_key_exists('q', $criteria)) {
            $newCriteria->where(Criteria::expr()->contains('source', $criteria['q']))
                ->orWhere(Criteria::expr()->contains('description', $criteria['q']));
        }

        if (array_key_exists('prospect', $criteria)) {
            $newCriteria->andWhere(Criteria::expr()->in('prospect', $criteria['prospect']));
        }

        return $this->matching($newCriteria);
    }
}
