<?php
/**
 * @file
 * Code for the Groups Home feature.
 */

include_once 'groups_homepage.features.inc';

/**
 * Implements hook_block_info().
 */
function groups_homepage_block_info() {
  $blocks['groups_homepage_welcome'] = array(
    'info' => t('Groups welcome block'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['groups_community_map'] = array(
    'info' => t('Groups community map'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['groups_community_stats']= array(
    'info' => t('Groups community stats'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['groups_find_nearby']= array(
    'info' => t('Groups find nearby'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['groups_community_banner'] = array(
    'info' => t('Community Banner'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['groups_community_guides'] = array(
    'info' => t('Community Guides'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function groups_homepage_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'groups_homepage_welcome':
      $block['content'] = variable_get('groups_welcome_body', "Can't find one nearby? Want to start one? The <a href='https://wiki.openstack.org/wiki/Teams#Community_team'>OpenStack International Community team</a> is your main contact point. Join the <a href='http://lists.openstack.org/cgi-bin/mailman/listinfo/community'>mailing list</a> and read the <a href='https://groups.openstack.org/tips'>HowTo page</a> if you are hosting or want to start a user group with meetups, hackathons and other social events talking about OpenStack and free/libre open source software for the cloud.");
      $block['subject'] = variable_get('groups_welcome_title', 'Welcome to OpenStack User Groups!');
      break;
    case 'groups_community_map':
      $block['content'] = theme('community_map', array());
      $block['subject'] = 'Community map';
      drupal_add_css(drupal_get_path('module', 'groups_homepage') . '/groups_homepage.css');
      drupal_add_js(drupal_get_path('module', 'groups_homepage'). '/groups_homepage.js');
      break;
    case 'groups_community_stats':
      $stats = array(
        'people' => variable_get('groups_stat_members', 0),
        'countries' => variable_get('groups_stat_countries', 0),
        'user-groups' => variable_get('groups_stat_groups', 0),
      );
      $block['subject'] = 'Community stats';
      $block['content'] = theme('community_stats', array('stats' => $stats));
      break;
    case 'groups_find_nearby':
      $block['content'] = theme('groups_find_nearby', array());
      $block['subject'] = 'Find nearby groups';
      break;
    case 'groups_community_banner':
      $block['content'] = theme('groups_community_banner', array());
      $block['subject'] = 'Community Banner';
      break;
    case 'groups_community_guides':
      $menu = menu_navigation_links('menu-content-menu');
      $block['content'] = theme('links__menu_content_menu', array('links' => $menu));;
      $block['subject'] = 'Community Guides';
      break;
  }
  return $block;
}

/**
 * Implements hook_menu_alter()
 * remove search main menu item
 */
function groups_homepage_menu_alter(&$items) {
  unset($items['search']);
}

/**
 * Implements hook_theme()
 * @return multitype:number
 */

function groups_homepage_theme() {
  $module_path = drupal_get_path('module', 'groups_homepage');
  $base = array(
      'path' => "$module_path/templates",
  );
  return array(
    'community_stats' => $base + array(
      'template' => 'community_stats',
      'variables' => array('stats' => NULL,),
    ),
    'groups_find_nearby' => $base + array(
      'template' => 'groups_find_nearby',
      'variables' => array(),
    ),
    'community_map' => $base + array(
      'template' => 'community_map',
      'variables' => array(),
    ),
    'groups_community_banner' => $base + array(
      'template' => 'community_banner',
      'variables' => array(),
    ),
  );
}

/**
 * Implements of hook_cron()
 *
 * Update community statistics, defaults to 1 hour run.
 */

function groups_homepage_cron() {
  $time = REQUEST_TIME;
  $last_cron = variable_get('groups_stat_last_cron', 0);
  $cron_schedule = variable_get('groups_stat_schedule_cron', 3600);
  if ($time - $last_cron > $cron_schedule) {
    groups_homepage_update_stats();
    variable_set('groups_stat_last_cron', $time);
  }
}

/**
 * Extract a stat element from openstack.org html source.
 * @param DOMDocument $doc
 * @param String $elementName
 * @return value of stat element, if processing fails, return null.
 */

function groups_homepage_get_stat_element($doc, $elementName) {
  $memberDiv = $doc->getElementById($elementName);
  if (isset($memberDiv)) {
    $element = $memberDiv->getElementsByTagName('p')->item(0);
    if (isset($element)) {
      return intval($element->nodeValue);
    }
  }
  return null;
}

/**
 * Update groups statistics. Number of members and countries coming from
 * openstack.org, and user group number comes from internal content.
 */

function groups_homepage_update_stats() {
  try {
    // extract stats from openstack.org
    $payload = file_get_contents('http://www.openstack.org');
    $doc = new DOMDocument();
    @$doc->loadHTML($payload);
    $members = groups_homepage_get_stat_element($doc, 'members');
    $countries = groups_homepage_get_stat_element($doc, 'countries');
    if (($members != null) && ($members > 0)) {
      variable_set('groups_stat_members', $members);
    }
    if (($countries != null) && ($countries > 0)) {
      variable_set('groups_stat_countries', $countries);
    }
    // count group nodes
    $query = 'SELECT COUNT(*) amount FROM {node} n '.
             'WHERE n.type = :type';
    $result = (db_query($query, array(':type' => 'group'))->fetch());
    $groups = (int)$result->amount;
    if (($groups != null) && ($groups > 0)) {
      variable_set('groups_stat_groups', $groups);
    }
    watchdog('update community stats', 'members:%members countries:%countries groups:%groups',
      array('%members' => $members, '%countries' => $countries, '%groups'=> $groups));
  } catch (Exception $e) {
    watchdog_exception('update community stats', $e);
  }
}

/**
 * Implements hook_views_pre_build
 *
 * Override load more pager of commons_events_upcoming views
 * panel_pane_2 display.
 */
function groups_homepage_views_pre_build(&$view) {
  if ($view->name == 'commons_events_upcoming' &&
      $view->current_display == 'panel_pane_2') {
    $pager = array(
      'type' => 'some',
      'options' => array(
        'offset' => intval(0)
      ),
    );
    $view->display_handler->set_option('pager', $pager);
    $view->init_pager();
    $view->set_items_per_page('5');
    $view->display_handler->set_option('title', t('Upcoming Events'));
  }
}
