<?php

namespace Club\RankingBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * RankingRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RankingRepository extends EntityRepository
{
  public function getTop(\Club\RankingBundle\Entity\Ranking $ranking, $limit=4)
  {
    $rank = $this->_em->createQueryBuilder()
      ->select('lt')
      ->from('ClubRankingBundle:RankingEntry', 'lt')
      ->where('lt.ranking = :ranking')
      ->orderBy('lt.point', 'DESC')
      ->setMaxResults($limit)
      ->setParameter('ranking', $ranking->getId())
      ->getQuery()
      ->getResult();

    return $rank;
  }

  public function getUsersBySearch(\Club\RankingBundle\Entity\Ranking $ranking, $query)
  {
    return $this->_em->createQueryBuilder()
      ->select(array('l', 'u'))
      ->from('ClubRankingBundle:Ranking','l')
      ->leftJoin('l.users', 'u')
      ->leftJoin('u.profile','p')
      ->where('l.id = :ranking')
      ->andWhere("u.member_number = :number OR CONCAT(CONCAT(p.first_name,' '), p.last_name) LIKE :query")
      ->setParameter('ranking', $ranking->getId())
      ->setParameter('number', $query)
      ->setParameter('query', '%'.$query.'%')
      ->getQuery()
      ->getOneOrNullResult();
  }

  public function getByMatch(\Club\MatchBundle\Entity\Match $match)
  {
      return $this->createQueryBuilder('r')
          ->join('r.matches', 'm', 'with', 'm.match = :match_id')
          ->setParameter('match_id', $match->getId())
          ->getQuery()
          ->getOneOrNullResult();
  }

  public function getRecentMatches(\Club\RankingBundle\Entity\Ranking $ranking, $limit=10)
  {
    $matches = $this->_em->createQueryBuilder()
        ->select('m')
        ->from('ClubRankingBundle:Match', 'm')
        ->where('m.ranking = :ranking_id')
        ->orderBy('m.id', 'DESC')
        ->setMaxResults($limit)
        ->setParameter('ranking_id', $ranking->getId())
        ->getQuery()
        ->getResult();

    if (!$matches) return false;

    $ids = array();
    foreach ($matches as $match) {
        $ids[] = $match->getMatch()->getId();
    }

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