<?php 

namespace NPS\Repository;

use NPS\DependencyInjection\IExpertSystemBridge;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use NPS\Entity\ConsultationEntity;
use NPS\Model\Consultation;
use NPS\Model\KnowledgeBase;
use NPS\Model\User;
use NPS\Factory\IObjectFactory;
use NPS\Factory\ConsultationFactory;

/**
 * Consultation repository class
 * @author Lukas Korinek
 */
final class ConsultationRepository implements IObjectRepository
{

    /** @var EntityRepository $entityRepository */
    private $entityRepository;

    /** @var IObjectFactory $factory */
    private $factory;

    public function __construct(EntityManagerInterface $em, ConsultationFactory $factory)
    {
        $this->entityRepository = $em->getRepository(ConsultationEntity::class);
        $this->factory = $factory;
    }

    /**
     * Gets a consultation by id
     * @param int $id 
     * @return Consultation|null
     */
    public function getById($id)
    {
        if(!$consultation = $this->entityRepository->find($id))
        {
            return null;
        }
        
        return $this->factory->make($consultation);
    }

    /**
     * Gets consultation history by a user 
     * @param User $user 
     * @param int $offset Result offset
     * @param int $limit Result limit
     * @param array|null $knowledgeBaseIds To filter history by knowledge base ids
     * @param bool $flaggedOnly To filter only flagged consultations
     * @return array
     */
    public function getConsultationHistory(User $user, $offset, $limit, array $knowledgeBaseIds = NULL, $flaggedOnly = false)
    {
        $builder = $this
            ->entityRepository
            ->createQueryBuilder('c')
            ->andWhere('IDENTITY(c.user) = :userId')
            ->setParameter('userId', $user->getId())
            ->setMaxResults($limit)
            ->setFirstResult($offset)
            ->orderBy('c.id', 'desc');

        if($knowledgeBaseIds)
        {
            $builder = $builder->andWhere('IDENTITY(c.base) IN (:ids)')->setParameter('ids', $knowledgeBaseIds);
        }

        if($flaggedOnly)
        {
            $builder = $builder->andWhere('c.flagged = 1');
        }
        
        return array_map(function($consultation)
        {
            return $this->factory->make($consultation);
        }, $builder->getQuery()->getResult());
    }

}

