<?php 

namespace NPS\Repository;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use NPS\Entity\IEntity;
use NPS\Entity\AbstractUserQueryEntity;
use NPS\Factory\UserQueryFactory;
use NPS\Entity\ErrorReportingQueryEntity;
use NPS\Entity\UserQuestionQueryEntity;

/**
 * User query repository class
 * @author Lukas Korinek
 */
final class UserQueryRepository implements IObjectRepository
{

    const USER_QUERY_ERROR_REPORTING = 'error_reporting';
    const USER_QUERY_QUESTION = 'question';

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

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

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

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

    public function __construct(EntityManagerInterface $em, UserQueryFactory $factory)
    {
        $this->entityRepository = $em->getRepository(AbstractUserQueryEntity::class);
        $this->errorReportingEntityRepository = $em->getRepository(ErrorReportingQueryEntity::class);
        $this->userQuestionEntityRepository = $em->getRepository(UserQuestionQueryEntity::class);
        $this->factory = $factory;
    }

    /**
     * @inheritdoc
     */
    public function getById($id)
    {
        $entity = $this->entityRepository->find($id);
        return $entity ? $this->factory->make($entity) : null;
    }

    /**
     * Lists user queries with the desired type
     * @param int $type Requested user query type
     * @param int $limit 
     * @param int $offset
     * @return array
     */
    public function getAll($type, $limit = 50, $offset = 0)
    {
        switch($type)
        {
            case self::USER_QUERY_ERROR_REPORTING: $entitites = $this->errorReportingEntityRepository->findBy([], [], $limit, $offset); break;
            case self::USER_QUERY_QUESTION: $entitites = $this->userQuestionEntityRepository->findBy([], [], $limit, $offset); break;
        }

        return array_map(function($entity){
            return $this->factory->make($entity);
        }, $entitites);
    }

}

