<?php

/**
 * @file
 * User Relationships Views integration.
 * @author Alex Karshakevich http://drupal.org/user/183217
 */

/**
 *  Implements hook_views_api().
 */
function user_relationship_views_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'user_relationship_views'),
  );
}

/**
 * Implements hook_menu().
 */
function user_relationship_views_menu() {
  // Path is not admin/build/views due to menu complications with the wildcards from
  // the generic ajax callback.
  $items['admin/views/ajax/autocomplete/user_relationships_type'] = array(
    'page callback' => 'user_relationship_views_ajax_autocomplete_relationships_type',
    'access callback' => 'user_access',
    'access arguments' => array('view user relationships'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback for views user relationship types autocomplete
 */
function user_relationship_views_ajax_autocomplete_relationships_type($string = '') {
  // The same implementation as in admin/views/ajax/autocomplete/user
  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $array = drupal_explode_tags($string);

  // Fetch last tag
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string != '') {
    $prefix = count($array) ? implode(', ', $array) . ', ' : '';


    foreach (user_relationships_types_load() as $rtype) {
      if (stripos($rtype->name, $string) === 0) {
        $n = $rtype->name;
        // Commas and quotes in terms are special cases, so encode 'em.
        if (strpos($rtype->name, ',') !== FALSE || strpos($rtype->name, '"') !== FALSE) {
          $n = '"' . str_replace('"', '""', $rtype->name) . '"';
        }
        $matches[$prefix . $n] = check_plain(user_relationships_type_get_name($rtype));
      }
    }
  }

  drupal_json_output($matches);
}
