<?php

namespace Club\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * FilterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class FilterRepository extends EntityRepository
{
  public function findActive(\Club\UserBundle\Entity\User $user)
  {
    $filter = $this->_em->getRepository('ClubUserBundle:Filter')->findOneBy(array(
      'user' => $user->getId(),
      'active' => 1
    ));

    if (!$filter) {
      $filter = $this->createFilter($user);
      $filter->setActive(1);

      $this->_em->flush();
    }

    return $filter;
  }

  public function activateFilter(\Club\UserBundle\Entity\User $user, \Club\UserBundle\Entity\Filter $filter)
  {
    $old_filter = $this->findActive($user);
    $old_filter->setActive(0);

    $this->_em->persist($old_filter);

    $filter->setActive(1);
    $this->_em->persist($filter);
  }

  public function createFilter(\Club\UserBundle\Entity\User $user)
  {
    $filter = new \Club\UserBundle\Entity\Filter;
    $filter->setFilterName('Working');
    $filter->setActive(0);
    $filter->setUser($user);

    $this->_em->persist($filter);

    return $filter;
  }

  public function deleteAttributes(\Club\UserBundle\Entity\Filter $filter)
  {
    return $this->_em->createQueryBuilder()
      ->delete('ClubUserBundle:FilterAttribute', 'fa')
      ->where('fa.filter = :filter')
      ->setParameter('filter', $filter->getId())
      ->getQuery()
      ->getResult();
  }
}
