<?php

namespace Club\MatchBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * MatchRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MatchRepository extends EntityRepository
{
  public function getLatest(\Club\UserBundle\Entity\User $user, $limit=10)
  {
    $r = $this->_em->createQueryBuilder()
      ->select('t, mt, m')
      ->from('ClubMatchBundle:Team', 't')
      ->join('t.users', 'u')
      ->join('t.match_teams', 'mt')
      ->join('mt.match', 'm')
      ->where('u.id = :user')
      ->setParameter('user', $user->getId())
      ->setMaxResults($limit)
      ->getQuery()
      ->getResult();

    if (!$r) return false;

    $ids = array();
    foreach ($r as $team) {
        foreach ($team->getMatchTeams() as $match_team) {
            $ids[] = $match_team->getMatch()->getId();
        }
    }

    return $this->_em->createQueryBuilder()
        ->select('m')
        ->from('ClubMatchBundle:Match', 'm')
        ->where('m.id IN (:ids)')
        ->setParameter('ids', $ids)
        ->getQuery()
        ->getResult();
  }

  public function getPaginator($results, $page)
  {
      $offset = ($page < 1) ? 1 : ($page-1)*$results;

      $dql = "SELECT m FROM ClubMatchBundle:Match m ORDER BY m.id DESC";
      $query = $this->_em->createQuery($dql)
          ->setFirstResult($offset)
          ->setMaxResults($results);

      return new \Doctrine\ORM\Tools\Pagination\Paginator($query, false);
  }
}
