<?php

namespace Club\LogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * LogRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class LogRepository extends EntityRepository
{
  public function findAll()
  {
    return $this->_em->createQueryBuilder()
      ->select('l')
      ->from('ClubLogBundle:Log','l')
      ->orderBy('l.id','DESC')
      ->getQuery()
      ->getResult();
  }

  public function getCount()
  {
    $qb = $this->getQueryBuilder();

    return count($qb->getQuery()->getResult());
  }

  public function getWithPagination($offset = 0, $limit = 0)
  {
    $qb = $this->getQueryBuilder();

    if ((isset($offset)) && (isset($limit))) {
      if ($limit > 0) {
        $qb->setFirstResult($offset);
        $qb->setMaxResults($limit);
      }
    }

    return $qb
      ->getQuery()
      ->getResult();
  }

  private function getQueryBuilder()
  {
    return $this->_em->createQueryBuilder()
      ->select('l')
      ->from('ClubLogBundle:Log','l')
      ->orderBy('l.id', 'DESC');
  }

  public function getRecent($limit=10)
  {
    return $this->getQueryBuilder()
      ->select('l,u,p')
      ->where('l.user IS NOT NULL')
      ->join('l.user', 'u')
      ->join('u.profile', 'p')
      ->setMaxResults($limit)
      ->getQuery()
      ->getResult();
  }

  public function getByUser(\Club\UserBundle\Entity\User $user)
  {
      return $this->_em->createQueryBuilder()
          ->select('l')
          ->from('ClubLogBundle:Log', 'l')
          ->where('l.user = :user')
          ->orderBy('l.id', 'DESC')
          ->setMaxResults(20)
          ->setParameter('user', $user->getId())
          ->getQuery()
          ->getResult();
  }
}
