<?php 

namespace NPS\Repository;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use NPS\Entity\UserEntity;
use NPS\Factory\UserFactory;
use NPS\Entity\IEntity;

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

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

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

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

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

    /**
     * Gets a user by email
     * @param string $email 
     * @return User|null
     */
    public function getByEmail($email)
    {
        $entity = $this->entityRepository->findOneBy(['email' => $email]);
        return $entity ? $this->factory->make($entity) : null;
    }

    /**
     * Gets all users within the app
     * @param int $limit 
     * @param int $offset
     * @return array
     */
    public function getAll($limit, $offset)
    {
        $entities = $this->entityRepository->findBy([], ['username' => 'asc'], $limit, $offset);

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

