<?php
/**
 * @file
 * A block module that displays autoswitching infos.
 */

include_once 'diy_info_sidebar.features.inc';

/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *     Which path of the site we're using to display help
 * @param arg
 *     Array that holds the current path as returned from arg() function
 */
function diy_info_sidebar_help($path, $arg) {
    switch ($path) {
        case 'admin/help#diy_info_sidebar':
            return '<p>' . t('Displays autoswitching info blocks') . '</p>';
            break;
    }
}

/**
 * Implements hook_block_info().
 */
function diy_info_sidebar_block_info() {
    $terms = diy_info_sidebar_get_vocabulary();

    $blocks = array();

    foreach ($terms as $tid => $name) {
        if ($tid === 0) continue;

        $blocks['diy_info_sidebar_' . $tid] = array(
            // The name that will appear in the block list.
            'info' => t('DIY Info - ') . $name,
            // Default setting.
            'cache' => DRUPAL_CACHE_PER_ROLE,
        );
    }

    return $blocks;
}

function diy_info_sidebar_block_view($delta = '') {
    if (substr($delta, 0, strlen('diy_info_sidebar')) === 'diy_info_sidebar') {
        $tid = substr($delta, strlen('diy_info_sidebar_'));

        if (false === diy_info_sidebar_has_contents($tid)) {
            return;
        }

        $terms = diy_info_sidebar_get_vocabulary();

        $termName = '';
        if (isset($terms[$tid])) {
            $termName = $terms[$tid];
        } else {
            return array('subject' => 'error', 'content' => 'no term found with id ' . $tid);
        }

        $block['subject'] = t('Beispiele @term', array('@term' => $termName));
        if (user_access('access content')) {

            $arg = variable_get('diy_info_sidebar_filter_' . $tid, 0);
            $autointerval = variable_get('diy_info_sidebar_autointerval_' . $tid, 0);
            $params = array(
                'tid' => $tid
            );
            if (is_numeric($autointerval) && !empty($autointerval)) {
                $params['autointerval'] = $autointerval;
            }

            $block['content'] = diy_info_sidebar_replace_user(theme('diy_info_sidebar_block', $params));
        }

        return $block;
    }
}

function diy_info_sidebar_replace_user($str) {
    global $user;
    if (!$user || !isset($user->uid) || $user->uid == 0) {
        $str = str_replace('[userid]', '', $str);
        $str = str_replace('[username]', '', $str);
        return $str;
    }
    $str = str_replace('[userid]', $user->uid, $str);
    $str = str_replace('[username]', $user->name, $str);
    return $str;
}

function diy_info_sidebar_has_contents($tid) {
    if (!is_numeric($tid) || $tid <= 0) {
        return false;
    }
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'info')
        ->fieldCondition('field_area', 'tid', $tid, '=') // node written by a specific user
        ->propertyCondition('status', 1) // published nodes
        ->addMetaData('account', user_load(1)); // Run the query as user 1.

    $result = $query->execute();
    if (isset($result['node'])) {
        $infopages = array_keys($result['node']);
        $infopages_entity = entity_load('node', $infopages);
        return array_values($infopages);
    }

    return false;
}

/*
 * Implements HOOK_theme().
 */
function diy_info_sidebar_theme($existing, $type, $theme, $path) {
    return array(
        'diy_info_sidebar_block' => array(
            'template'      => 'diy_info_sidebar_block',
            'variables'     => array(
                'autointerval'  => NULL,
            )
        )
    );
}


function diy_info_sidebar_init() {
    drupal_add_js(drupal_get_path('module', 'diy_info_sidebar') .'/autopager.js');
    drupal_add_css(drupal_get_path('module', 'diy_info_sidebar') .'/diy_info_sidebar.css');
}

/**
 * Implements hook_block_configure().
 */
function diy_info_sidebar_block_configure($delta = '') {
    $form = array();

    if (substr($delta, 0, strlen('diy_info_sidebar')) === 'diy_info_sidebar') {
        $tid = substr($delta, strlen('diy_info_sidebar_'));

        $form['diy_info_sidebar_height_' . $tid] = array(
            '#type' => 'textfield',
            '#title' => t('Fixed height of content in pixel'),
            '#default_value' => variable_get('diy_info_sidebar_height_' . $tid, ''),
            '#size' => 5,
            '#maxlength' => 3
        );

        $form['diy_info_sidebar_autointerval_' . $tid] = array(
            '#type' => 'textfield',
            '#title' => t('Interval in milliseconds the pager automatically jumps'),
            '#default_value' => variable_get('diy_info_sidebar_autointerval_' . $tid, ''),
            '#size' => 7,
            '#maxlength' => 5
        );
    }
    return $form;
}

function diy_info_sidebar_get_vocabulary() {
    static $terms;
    if ($terms) return $terms;
    $tree = taxonomy_get_tree(
        taxonomy_vocabulary_machine_name_load('info_bereiche')->vid
    );
    $terms = array(
        t('-- select a taxonomy term --')
    );
    foreach ($tree as $term) {
        $terms[$term->tid] = $term->name;
    }
    return $terms;
}

/**
 * Implements hook_block_save().
 */
function diy_info_sidebar_block_save($delta = '', $edit = array()) {
    if (substr($delta, 0, strlen('diy_info_sidebar')) === 'diy_info_sidebar') {
        $tid = substr($delta, strlen('diy_info_sidebar_'));

        // Saving the block height
        $value = $edit['diy_info_sidebar_height_' . $tid];
        variable_set(
            'diy_info_sidebar_height_' . $tid,
            $value
        );

        // Saving the taxonomy term id
        $value = $edit['diy_info_sidebar_autointerval_' . $tid];
        variable_set(
            'diy_info_sidebar_autointerval_' . $tid,
            $value
        );
    }
}