<?php

/**
 * Implementation of hook_menu()
 */
function services_ccc_menu() {
  $items['admin/structure/services_client/conditional_taxonomy'] = array(
    'title' => 'Custom Condition',
    'description' => 'Send node to remote site based on taxonomy',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('services_ccc_settings'),
    'access arguments' => array('administer services client'),
    'weight' => 20,
    'type' => MENU_LOCAL_TASK,
  );
  
  return $items;
}

function services_ccc_settings() {
  $form['services_ccc_connection_taxonomy'] = array(
    '#type' => 'textfield',
    '#title' => 'Field containing taxonomy terms',
    '#default_value' => variable_get('services_ccc_connection_taxonomy', NULL),
  );
  return system_settings_form($form);
}

/**
 * Implementation of hook_node_insert()
 * 
 * @param object $node
 */
function services_ccc_node_insert($node) {
  services_ccc_node_send($node);
}

/**
 * Implementation of hook_node_updaet()
 * 
 * @param object $node
 */
function services_ccc_node_update($node) {
  services_ccc_node_send($node);
}

/**
 * Get the remote connections listed in the node and send to them
 * 
 * @param object $node
 * @return boolean
 */
function services_ccc_node_send($node) {
  $vocab_field = variable_get('services_ccc_connection_taxonomy', NULL);
  $conns_to_send = array();
  
  // If the vocab field is not set, then bail.
  if (!$vocab_field) {
    return;
  }
  
  // Get our tids from the node
  if (isset($node->{$vocab_field})) {
    $lang = field_language('node', $node, $vocab_field);
    foreach($node->{$vocab_field}[$lang] as $num => $term) {
     $conns_to_send[] = taxonomy_term_load($term['tid'])->name;
    }
  }

  // We have cons, lets send to those bad boys
  if (!empty($conns_to_send)) {
    services_client_data_process($node, 'node_save', NULL, $conns_to_send, TRUE);
  }
}
