<?php

/**
 * @file
 * Provides integration between Relation and UUID modules.
 */

/**
 * Implements hook_entity_info_alter().
 */
function relation_uuid_entity_info_alter(&$entity_info) {
  $entity_info['relation']['uuid'] = TRUE;
  $entity_info['relation']['entity keys']['uuid'] = 'uuid';
  $entity_info['relation']['entity keys']['revision uuid'] = 'vuuid';
}

/**
 * Implements hook_schema_alter().
 */
function relation_uuid_schema_alter(&$schema) {
  $field = uuid_schema_field_definition();
  $schema['relation']['fields']['uuid'] = $field;
  $schema['relation']['indexes']['uuid'] = array('uuid');
  $schema['relation_revision']['fields']['vuuid'] = $field;
  $schema['relation_revision']['indexes']['vuuid'] = array('vuuid');
}

/**
 * Implements hook_entity_uuid_load().
 */
function relation_uuid_entity_uuid_load(&$entities, $entity_type) {
  if ($entity_type == 'relation') {
    entity_property_id_to_uuid($entities, 'user', array('uid', 'revision_uid'));
  }
}

/**
 * Implements hook_entity_uuid_presave().
 */
function relation_uuid_entity_uuid_presave(&$entity, $entity_type) {
  if ($entity_type == 'relation') {
    entity_property_uuid_to_id($entity, 'user', array('uid', 'revision_uid'));
  }
}

/**
 * Implements hook_field_uuid_load().
 */
function relation_endpoint_field_uuid_load($entity_type, $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as  $delta => $item) {
    $item_object = (object) $item;
    entity_property_id_to_uuid($item_object, $item['entity_type'], 'entity_id');
    $items[$delta]['entity_id'] = $item_object->entity_id;
  }
}

/**
 * Implements hook_field_uuid_presave().
 */
function relation_endpoint_field_uuid_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as  $delta => $item) {
    $item_object = (object) $item;
    entity_property_uuid_to_id($item_object, $item['entity_type'], 'entity_id');
    $items[$delta]['entity_id'] = $item_object->entity_id;
  }
}
