<?php

namespace App\Repository\FileAssociation;

use App\Entity\FileAssociationCampaign;
use App\Service\FileAssociationCampaignRepositoryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\Criteria;
use Symfony\Bridge\Doctrine\RegistryInterface;

final class DoctrineFileAssociationCampaignRepository extends ServiceEntityRepository implements FileAssociationCampaignRepositoryInterface
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, FileAssociationCampaign::class);
    }

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

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

    /**
     * @param FileAssociationCampaign $fileAssociationCampaign
     *
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(FileAssociationCampaign $fileAssociationCampaign): void
    {
        $this->_em->remove($fileAssociationCampaign);
        $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();
    }

    /**
     * @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): \Doctrine\Common\Collections\Collection
    {
        $newCriteria = Criteria::create()
            ->setFirstResult($offset)
            ->setMaxResults($limit);

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

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

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

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

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

        return $result->count();
    }
}
