<?php

/*
 * This file is part of Phraseanet
 *
 * (c) 2005-2014 Alchemy
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Alchemy\Phrasea\Model\Repositories;

use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Model\Entities\UsrList;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

    /**
     * Get all lists readable for a given User
     *
     * @param  User                                         $user
     * @return UsrList[]
     */
    public function findUserLists(User $user)
    {
        $dql = 'SELECT l FROM Phraseanet:UsrList l
              JOIN l.owners o
            WHERE o.user = :usr_id';

        $params = [
            'usr_id' => $user->getId(),
        ];

        $query = $this->_em->createQuery($dql);
        $query->setParameters($params);

        return $query->getResult();
    }

    /**
     *
     * @param  User    $user
     * @param  int     $list_id
     * @return UsrList
     */
    public function findUserListByUserAndId(User $user, $list_id)
    {
        $list = $this->find($list_id);

        /* @var $list UsrList */
        if (null === $list) {
            throw new NotFoundHttpException('List is not found.');
        }

        if (!$list->hasAccess($user)) {
            throw new AccessDeniedHttpException('You have not access to this list.');
        }

        return $list;
    }

    /**
     * Search for a UsrList like '' with a given value, for a user
     *
     * @param  User                                         $user
     * @param  type                                         $name
     * @return \Doctrine\Common\Collections\ArrayCollection
     */
    public function findUserListLike(User $user, $name)
    {
        $dql = 'SELECT l FROM Phraseanet:UsrList l
              JOIN l.owners o
            WHERE o.user = :usr_id AND l.name LIKE :name';

        $params = [
            'usr_id' => $user->getId(),
            'name'   => $name . '%'
        ];

        $query = $this->_em->createQuery($dql);
        $query->setParameters($params);

        return $query->getResult();
    }
}
