<?php

namespace Club\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * GroupRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GroupRepository extends EntityRepository
{
  public function getDynamicUsers(\Club\UserBundle\Entity\Group $group)
  {
    $filter = new \Club\UserBundle\Entity\Filter();
    if ($group->getGender() != null) {
      $attr = new \Club\UserBundle\Entity\FilterAttribute();
      $attr->setAttribute('gender');
      $attr->setValue($group->getGender());
      $filter->addAttributes($attr);
    }
    if ($group->getMaxAge() != null) {
      $attr = new \Club\UserBundle\Entity\FilterAttribute();
      $attr->setAttribute('max_age');
      $attr->setValue($group->getMaxAge());
      $filter->addAttributes($attr);
    }
    if ($group->getMinAge() != null) {
      $attr = new \Club\UserBundle\Entity\FilterAttribute();
      $attr->setAttribute('min_age');
      $attr->setValue($group->getMinAge());
      $filter->addAttributes($attr);
    }
    if ($group->getActiveMember() != null) {
      $attr = new \Club\UserBundle\Entity\FilterAttribute();
      $attr->setAttribute('active');
      $attr->setValue(1);
      $filter->addAttributes($attr);
    }

    return $this->_em->getRepository('ClubUserBundle:User')->getUsers($filter);
  }

  public function getOneGroupByRoles(array $roles)
  {
    return $this->_em->createQueryBuilder()
      ->select('g')
      ->from('ClubUserBundle:Group', 'g')
      ->leftJoin('g.role', 'r')
      ->where('r.role_name IN (:roles)')
      ->setParameter('roles', $roles)
      ->setMaxResults(1)
      ->getQuery()
      ->getOneOrNullResult();
  }

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

      $dql = "SELECT g FROM ClubUserBundle:Group g ORDER BY g.group_name DESC";
      $query = $this->_em->createQuery($dql)
          ->setFirstResult($offset)
          ->setMaxResults($results);

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