<?php

/**
 *
 * @author cquintin
 *
 */
class ThdUtil extends sfToolKit
{
    // Normalized chars
    private static $normalizedChars = Array(
      'à' => 'a', 'â' => 'a', 'ä' => 'a',
      'é' => 'e', 'è' => 'e', 'ë' => 'e', 'ê' => 'e',
      'ï' => 'i', 'î' => 'i',
      'ö' => 'o', 'ô' => 'o',
      'ü' => 'u', 'û' => 'u',
      'ç' => 'c');

    static public function normalizeText($text)
    {
      // replace all non letters width normalized characters
      $text = mb_strtolower(trim($text), 'UTF-8');
      $text = strtr($text, self::$normalizedChars);
      $text = preg_replace('/\W+/', '-', $text);
      $text = trim($text, '-');
      return $text;
    }

    static public function cmpTagCloud($a, $b) {
      if ($a['count'] == $b['count']) {
        return 0;
      }

      return ($a['count'] > $b['count']) ? -1 : 1;
    }

    static public function processTagCloud($tagCloud, $nbItems, $maxScore=5) {
      $newTagCloud = $tagCloud;
      uasort($newTagCloud , 'ThdUtil::cmpTagCloud');

      // Apply limit
      $newTagCloud = array_slice($newTagCloud, 0, $nbItems);
      if (count($newTagCloud) == 0) return Array();

      // Get first tag. Assume it has a score of 5
      $tagsByScore = Array();
      $firstTagCount = $newTagCloud[0]['count'];
      $scoreRatio = $maxScore/$firstTagCount;

      foreach ($newTagCloud as $index=>$item) {
        $score = (int) ceil($item['count']*$scoreRatio);
        $newItem = Array(
          'tag' => $item['tag'],
          'count' => $score);

        if (!isset($tagsByScore[$score])) {
          $tagsByScore[$score] = Array();
        }

        $tagsByScore[$score][] = $newItem;
      }

      // Sort tags in random way
      $newTagCloud = Array();

      foreach (range($maxScore, 1) as $scoreIndex=>$score) {
        if (!isset($tagsByScore[$score])) continue;

        foreach ($tagsByScore[$score] as $itemIndex=>$item) {
          $cloudIndex = ($itemIndex*$maxScore) + $scoreIndex;
          $newTagCloud[$cloudIndex] = $item;
        }
      }

      ksort($newTagCloud);
      return $newTagCloud;
    }

    static public function getGlobalTagCloud($limit=10) {
      $tags = Array();

      
      //facet=true&facet.limit=-1&facet.field=tags
      $parameters = Array('facet'=>'true', 'facet.limit'=>"$limit", 'facet.field'=>'tags_exact' );
      
      $solr = uvmcSolrServicesManager::getInstance()->getService();
      $response = $solr->search("*:*", 0, 0, $parameters);
      $result = unserialize($response->getRawResponse());
      
      foreach ($result["facet_counts"]["facet_fields"]["tags_exact"] as $tag_name => $count) {
        $tags[] = Array('tag' => $tag_name, 'count' => (int) $count);
      }

      return $tags;

    }
}
