<?php

/**
 * Implements hook_menu().
 */
function joomla_myblog_menu() {
  $items = array();
  $items['admin/content/joomla_myblog_map'] = array(
    'title' => 'MyBlog tag mapping',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('joomla_myblog_map_form'),
    'access arguments' => array('administer joomla'),
    'description' => 'Set up mappings for MyBlog tags.',
    'type' =>  MENU_LOCAL_TASK ,
  );
  return $items;
}

/**
 *
 */
function joomla_myblog_map_form($form, &$form_state) {
  $vid = variable_get('joomla_myblog_vocabulary', 0);
  joomla_database_init();
  $vname = db_query('SELECT name FROM {taxonomy_vocabulary} WHERE vid = :vid', array(':vid' => $vid))->fetchField();
  if (!joomla_database_test()) {
    $form['error'] = array(
      '#markup' => '<p>' . t('The joomla database settings are not currently valid. Please set the correct database settings at <a href="@url">Joomla to Drupal settings</a> page', array('@url' => url('admin/config/content/joomla'))) . '</p>',
    );
    return $form;
  }
  $map = joomla_myblog_map();
  if ($vid == 0) {
    $form['error'] = array(
      '#markup' => '<p>' . t('To use this page, an existing vocabulary must be set under <em>Vocabulary for MyBlog tags</em> on the <a href="@url">Joomla to Drupal settings</a> page', array('@url' => url('admin/config/content/joomla'))) . '</p>',
    );
    return $form;
  }
  $term_select_options = array();
  $tree = taxonomy_get_tree($vid);
  if ($tree) {
    foreach ($tree as $term) {
      $choice = new stdClass();
      $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
      $term_select_options[] = $choice;
    }
  }
  $term_select = array(
    '#type' => 'select',
    '#title' => check_plain($vname) ,
    '#options' => $term_select_options,
    '#multiple' => 0,
    '#size' => 0,
    '#weight' => -15,
  );
  $form['joomla_myblog_map'] = array(
    '#type' => 'fieldset',
    '#title' => t('Tag mappings'),
    '#description' => t('It is possible to map each myblog category to an existing term in the vocabulary select for MyBlog tags.'),
    '#tree' => TRUE,
  );
  $tags = joomla_myblog_tags();
  foreach ($tags as $tag) {
    $form['joomla_myblog_map'][$tag->id] = $term_select;
    $form['joomla_myblog_map'][$tag->id]['#title'] = $tag->name;
    if (array_key_exists($tag->id, $map)) {
      $form['joomla_myblog_map'][$tag->id]['#default_value'] = $map[$tag->id];
    }
  }
  $form['joomla_myblog_map_submit'] = array(
    '#type' => 'submit',
  );
  return $form;
}

/**
 *
 */
function joomla_myblog_map_form_submit($form, &$form_state) {
  // TODO
  $tags = joomla_myblog_tags();
  foreach ($form_state['values']['joomla_myblog_map'] as $myblogcategoryid => $tid) {
    if (empty($tid)) {
      continue;
    }
    joomla_myblog_set_map($myblogcategoryid, $tid);
  }
}

/**
 *
 */
function joomla_myblog_tags() {
  db_set_active('joomla');
  $tags = array();
  $results = db_query("SELECT * FROM {myblog_categories}");
  foreach ($results as $tag) {
    $tags[] = $tag;
  }
  db_set_active();
  return $tags;
}

/**
 * Returns an array representing the current tag mapping.
 */
function joomla_myblog_map() {
  $map = array();
  $result = db_query('SELECT * FROM {joomla_myblog_categories}');
  while ($row = $result->fetchAssoc()) {
    $map[$row['myblogcategoryid']] = $row['tid'];
  }
  return $map;
}

/**
 *
 */
function joomla_myblog_set_map($myblogcategoryid, $tid) {
  $map = db_query('SELECT * FROM {joomla_myblog_categories} WHERE myblogcategoryid = :myblogcategoryid', array(':myblogcategoryid' => $myblogcategoryid))->fetch();
  if ($map) {
    if ($map->tid == $tid) {
      // Mapping does not need updating
      return NULL;
    }
    // Update the existing mapping
    $map->tid = $tid;
    return drupal_write_record('joomla_myblog_categories', $map, 'myblogcategoryid');
  }
  $map = new stdClass();
  $map->myblogcategoryid = $myblogcategoryid;
  $map->tid = $tid;
  // Create a new mapping
  return drupal_write_record('joomla_myblog_categories', $map);
}

/**
 * Implements hook_joomla().
 */
function joomla_myblog_joomla($op, $object, $joomla_object) {
  switch ($op) {
    case 'node':
      joomla_myblog_update_node($object, $joomla_object);
      break;
  }
}

/**
 *
 */
function joomla_myblog_update_node($node = NULL, $jcontent = NULL) {
  if ($node === NULL) {
    return;
  }
  db_set_active('joomla');
  // Check to see if there is a myblog tag for this content item
  $myblogcategory = db_query('SELECT mcc.category,mc.name FROM {myblog_content_categories} mcc JOIN {myblog_categories} mc on mc.id = mcc.category WHERE mcc.contentid = :contentid', array(':contentid' => $jcontent->id))->fetchObject();
  db_set_active();
  // If this is not a myblog content item, there's nothing left to do
  if (!is_object($myblogcategory) && !$myblogcategory->category) {
    return;
  }
  // Get the taxonomy term id for this myblog category
  $myblog_map = db_query('SELECT * FROM {joomla_myblog_categories} WHERE myblogcategoryid = :myblogcategoryid', array(':myblogcategoryid' => $myblogcategory->category))->fetch();
  $vid = joomla_myblog_get_vocabulary_id();
  if (!$myblog_map) {
    // Create a new taxonomy term
    $term = new stdClass();
    $term->name = $myblogcategory->name;
    $term->vid = $vid;
    taxonomy_term_save($term);
    $myblog_map = new stdClass();
    $myblog_map->myblogcategoryid = $myblogcategory->category;
    $myblog_map->tid = $term->tid;
    drupal_write_record('joomla_myblog_categories', $myblog_map);
  }
  // Create a node <-> taxonomy link
  $term_node = new stdClass();
  $term_node->tid = $myblog_map->tid;
  $term_node->nid = $node->nid;
  drupal_write_record('taxonomy_term_index', $term_node);
}

/**
 * Implements hook_form_FORMID_alter().
 */
function joomla_myblog_form_joomla_admin_settings_alter(&$form, &$form_state) {
  $form['joomla_myblog'] = array(
    '#type' => 'fieldset',
    '#weight' => -5,
    '#title' => t('MyBlog settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );
  $vocabularies = array(0 => '---');
  foreach (taxonomy_get_vocabularies() as $vocabulary) {
    $vocabularies[$vocabulary->vid] = $vocabulary->name;
  }
  $form['joomla_myblog']['joomla_myblog_vocabulary'] = array(
    '#type' => 'select',
    '#title' => t('Vocabulary for MyBlog tags'),
    '#description' => t('Select the vocabulary in which to place MyBlog tags.  If not set, a vocabulary named <em>MyBlog</em> will be created.'),
    '#options' => $vocabularies,
    '#default_value' => variable_get('joomla_myblog_vocabulary', 0)
  );
}

/**
 *
 */
function joomla_myblog_get_vocabulary_id() {
  static $vid;
  if ($vid) {
    return $vid;
  }
  if (!$vid = variable_get('joomla_myblog_vocabulary', 0)) {
    if (!$vid = db_query('SELECT vid FROM {vocabulary} WHERE name = "MyBlog"')->fetchField()) {
      $vocabulary = new stdClass();
      $vocabulary->name = 'MyBlog';
      $vocabulary->machine_name = str_replace(' ', '_', drupal_strtolower($vocabulary->name));
      $vocabulary->module = 'Joomla';
      taxonomy_vocabulary_save($vocabulary);
      $vid = $vocabulary->vid;
    }
  }
  return $vid;
}