<?php

namespace UserBundle\Repository;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Parameter;
use UserBundle\Entity\Recipient\AbstractRecipient;

/**
 * RecipientRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RecipientRepository extends EntityRepository
{

    /**
     * @param integer $owner   A User entity id.
     * @param integer $limit   How much results return.
     * @param string  $keyword Search keyword.
     * @param array   $exclude Array of excluded ids.
     *
     * @return AbstractRecipient[]
     */
    public function search(
        $owner,
        $limit,
        $keyword = '',
        array $exclude = []
    ) {
        $expr = $this->_em->getExpressionBuilder();
        $condition = $expr->andX($expr->eq('Recipient.owner', ':owner'));
        $parameters = new ArrayCollection([
            new Parameter('owner', $owner),
        ]);

        if ($keyword !== '') {
            $condition->add($expr->like('Recipient.name', ':keyword'));
            $parameters->add(new Parameter('keyword', '%'. $keyword .'%'));
        }

        if (count($exclude) > 0) {
            $condition->add($expr->notIn('Recipient.id', ':ids'));
            $parameters->add(new Parameter('ids', $exclude));
        }

        return $this->createQueryBuilder('Recipient')
            ->where($condition)
            ->setParameters($parameters)
            ->setMaxResults($limit)
            ->orderBy('Recipient.name')
            ->getQuery()
            ->getResult();
    }

    /**
     * @param integer $owner A User entity id.
     *
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function getListQueryBuilder($owner)
    {
        return $this->createQueryBuilder('Recipient')
            ->where('Recipient.owner = :owner')
            ->setParameter('owner', $owner);
    }
}
