<?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\UsrListOwner;
use Alchemy\Phrasea\Model\Entities\UsrList;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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

    /**
     *
     *
     * @param  UsrList $list
     * @param  type    $owner_id
     * @return UsrList
     */
    public function findByListAndOwner(UsrList $list, $owner_id)
    {
        $owner = $this->find($owner_id);

        /* @var $owner UsrListOwner */
        if (null === $owner) {
            throw new NotFoundHttpException('Owner is not found');
        }

        if ( ! $owner->getList()->getid() != $list->getId()) {
            throw new AccessDeniedHttpException('Owner and list mismatch');
        }

        return $owner;
    }

    /**
     *
     *
     * @param  UsrList $list
     * @param  type    $usr_id
     * @return UsrList
     */
    public function findByListAndUsrId(UsrList $list, $usr_id)
    {
        $dql = 'SELECT o FROM Phraseanet:UsrListOwner o
              JOIN o.list l
            WHERE l.id = :list_id AND o.user = :usr_id';

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

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

        try {
            $owner = $query->getSingleResult();
        } catch (NoResultException $e) {
            throw new NotFoundHttpException('Owner is not found', null, $e);
        }

        return $owner;
    }
}
