<?php
// $Id:$

/**
 * Implementation of hook_help().
 */
function termblocks_help($section) {
  switch ($section) {
    case 'admin/help#termblocks':
      return t('Termblocks offers the creation of blocks which list taxonomy terms by: most recent, random, most popular.');
  }
}

/**
 * Implementation of hook_menu().
 */
function termblocks_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/settings/termblocks',
      'title' => t('Term Blocks configuration'),
      'description' => t('Set the number of configurable blocks you want termblocks to offer.'),
      'access' => user_access('administer site configuration'),
      'callback' => 'drupal_get_form',
      'callback arguments' => 'termblocks_admin_settings',
    );
  }
  return $items;
}

/**
 * Our menu callback for our admin settings page.
 */
function termblocks_admin_settings() {
  $options = drupal_map_assoc(range(0, 10));

  $form = array();

  $form['blocks'] = array(
    '#type' => 'fieldset',
    '#title' => t('Term Blocks settings'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['blocks']['termblocks_num'] = array(
    '#type' => 'select',
    '#title' => t('Number of Terms Blocks'),
    '#description' => t('You can configure the behavior of these blocks in @url.', array('@url' => url('admin/build/blocks'))),
    '#default_value' => variable_get('termblocks_num', 0),
    '#options' => $options,
  );
  return system_settings_form($form);
}

/**
 * Specific settings for each block.
 */
function _termblocks_block_settings($block_num = '') {
  if ($block_num) {
    $form['termblocks'] = array(
      '#type' => 'fieldset',
      '#title' => t('Term Blocks settings'),
      '#description' => t('Here you can change the way you want your terms to display, as well as how many you want displayed.'),
    );
    $options = array('random' => 'Random', 'new' => 'Newest', 'popular' => 'Popular');
    if (module_exists('tagadelic')) {
      $options['tagadelic'] = 'Tag Cloud';
    }
    $form['termblocks']['termblocks_display_'. $block_num] = array(
      '#type' => 'select',
      '#title' => t('Display settings'),
      '#options' => $options,
      '#default_value' => variable_get('termblocks_display_'. $block_num, 'new'),
    );
    $form['termblocks']['termblocks_num_'. $block_num] = array(
      '#type' => 'textfield',
      '#size' => 3,
      '#title' => t('Number of terms'),
      '#description' => t('The number of terms you want displayed in this block. Enter 0 for an infinite number.'),
      '#default_value' => variable_get('termblocks_num_'. $block_num, '0'),
    );
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $key => $vocab) {
      $options[$vocab->vid] = $vocab->name;
    }
    $form['termblocks']['termblocks_vid_'. $block_num] = array(
      '#type' => 'select',
      '#title' => t('Vocabulary'),
      '#description' => t('Choose an optional category to limit results from.'),
      '#options' => $options,
      '#default_value' => variable_get('termblocks_vid_'. $block_num, 'NULL'),
    );
    return $form;
  }
}

/**
 * Implementation of hook_block().
 */
function termblocks_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $termblocks_num = variable_get('termblocks_num', 0);
      for ($i = 1; $i <= $termblocks_num; $i++) {
        $blocks[$i]['info'] = t('Term Block ') . $i;
      }
      return $blocks;
    case 'configure':
      return _termblocks_block_settings($delta);
    case 'save':
      variable_set('termblocks_num_'. $delta, $edit['termblocks_num_'. $delta]);
      variable_set('termblocks_display_'. $delta, $edit['termblocks_display_'. $delta]);
      variable_set('termblocks_vid_'. $delta, $edit['termblocks_vid_'. $delta]);
    case 'view':
      $block['content'] = termblocks_display_type($delta);
      return $block;
  }
}

/**
 * Display our blocks.  New, popular, random, or tag cloud.
 */
function termblocks_display_type($block_num = '') {
  if ($block_num) {
    $display = variable_get('termblocks_display_'. $block_num, 'new');
    $limit = variable_get('termblocks_num_'. $block_num, '0');
    $vocabulary = variable_get('termblocks_vid_'. $block_num, 'NULL');

    switch ($display) {
      case 'new':
        return termblocks_display($limit, $vocabulary, 'new');
        break;
      case 'popular':
        return termblocks_display($limit, $vocabulary, 'popular');
        break;
      case 'random':
        return termblocks_display($limit, $vocabulary, 'random');
        break;
      case 'tagadelic':
        return termblocks_display_tagadelic($limit, $vocabulary);
        break;
    }
  }
}

/**
 * Display the categories with the most recent posts.
 */
function termblocks_display($limit, $vocabulary, $display = 'new') {
  $query = 'SELECT t.name, t.tid FROM {term_data} t JOIN {term_node} tn ON t.tid = tn.tid JOIN {node} n ON tn.nid = n.nid';

  if ($vocabulary != NULL) {
    $query .= ' WHERE t.vid = '. $vocabulary;
  }
  if ($display == 'new') {
    $query .= ' ORDER BY n.created DESC';
  }
  if ($display == 'random') {
    $query .= ' ORDER BY RAND()';
  }
  if ($display == 'popular') {
    $query .= ' GROUP BY t.name, t.tid ORDER BY COUNT(*)';
  }
  //  if ($limit != '0') {
  //    $query .= ' LIMIT '. $limit;
  //  }
  $result = db_query($query);
  $items = array();

  while ($terms = db_fetch_array($result)) {
    $items[$terms['name']] = l($terms['name'], 'taxonomy/term/'. $terms['tid']);
  }
  // Our query doesn't seem to like to play well with ORDER BY and DISTINCT, so instead we do our logic here.
  if ($limit !== '0') {
    array_splice($items, $limit);
  }
  $output = theme('item_list', $items, $title);

  return $output;
}

function termblocks_display_tagadelic($limit, $vocabulary) {
  return theme('tagadelic_weighted', tagadelic_sort_tags(tagadelic_get_weighted_tags(array($vocabulary), '6', $limit)));
}
