<?php

  // include base peer class
  require_once 'model/om/BaseSnippetTagPeer.php';
  
  // include object class
  include_once 'model/SnippetTag.php';


/**
 * Skeleton subclass for performing query and update operations on the 'sn_tag' table.
 *
 * 
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package model
 */	
class SnippetTagPeer extends BaseSnippetTagPeer
{
  public static function getAllWithCount($max = 100)
  {
    $tags = array();

    $con = Propel::getConnection();
    $query = '
      SELECT t1.name AS tag,
      COUNT(t1.name) AS count
      FROM '.SnippetTagPeer::TABLE_NAME.' AS t1
      GROUP BY t1.name
      ORDER BY count DESC
    ';

    $stmt = $con->prepareStatement($query);
    $stmt->setLimit($max);
    $rs = $stmt->executeQuery();
    $max_popularity = 0;
    while ($rs->next())
    {
      $tags[$rs->getString('tag')] = $rs->getInt('count');
    }

    ksort($tags);

    return $tags;
  }
  
  public function getPopular($levels = 3, $floor = 0.2, $power = 0.4)
  {
    $all_tags = self::getAllWithCount(200);
    $max_count = max($all_tags);
    $tags = array();
    foreach($all_tags as $tag => $count)
    {
      if($count/$max_count > $floor)
      {
        $tags[$tag] = intval(($levels-1)*pow($count/$max_count, $power)+1);
      }
    }
    return $tags;
  }

  public static function getForSnippetsWithCount($snippets, $excluded_tags, $max = 100)
  {
    $snippet_ids = array();
    foreach($snippets as $snippet)
    {
      $snippet_ids[] = $snippet->getId();
    }

    $con = Propel::getConnection();
    $query = '
      SELECT '.SnippetTagPeer::NAME.' AS tag,
      COUNT('.SnippetTagPeer::NAME.') AS count
      FROM '.SnippetTagPeer::TABLE_NAME.'
      WHERE '.SnippetTagPeer::SNIPPET_ID.' IN ('.implode(' ,', $snippet_ids).')
      GROUP BY '.SnippetTagPeer::NAME.'
      ORDER BY '.SnippetTagPeer::NAME.' ASC
    ';

    $stmt = $con->prepareStatement($query);
    $stmt->setLimit($max);
    $rs = $stmt->executeQuery();

    $tags = array();
    while ($rs->next())
    {
      $tag = $rs->getString('tag');
      if(array_search($tag, $excluded_tags) === false)
      {
        $tags[$tag] = $rs->getInt('count');
      }
    }

    return $tags;
  }
}

