<?php

namespace AppBundle\Entity\Core\Repository;

use AppBundle\Entity\Organization\Organization;
use AppBundle\Entity\AccessAndFunction\Access;
use Doctrine\ORM\EntityRepository;

/**
 * Description of DocumentRepository
 *
 * @author sebastienhupin
 */
class DocumentRepository extends EntityRepository {
    
    /**
     * Find the template
     * 
     * @param type $name
     * @param Access $author
     * @param Organization $organization
     */
    public function getTemplate($name, Access $author = null, Organization $organization = null) {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder('t');
        
        $expr = $qb->expr();
        
        $qb->select('t');
        $qb->from($this->getClassName(), 't');
        $qb->where($expr->eq('t.slug',':name'))
            ->andWhere($expr->eq('t.template', ':template'))    
            ->andWhere($expr->orX(
                    $expr->eq('t.author', ':author'),
                    $expr->isNull('t.author')
            ))
            ->andWhere($expr->orX(
                    $expr->eq('t.organization', ':organization'),
                    $expr->isNull('t.organization')
            ));

        $qb->orderBy('t.author', 'DESC')
            ->addOrderBy('t.organization', 'DESC');
        
        $qb->setMaxResults(1);
        
        $qb->setParameter('name', $name);
        $qb->setParameter('template', true);
        $qb->setParameter('author', $author);
        $qb->setParameter('organization', $organization);        

        $result = $qb->getQuery()->getOneOrNullResult();

        return $result;
    }
}
