<?php

/**
 * @file
 * Location Entity module.
 */

/**
 * Implements hook_field_info_alter().
 */
function location_entity_field_info_alter(&$field_info) {
  // Location field type is defined in the location_cck module.
  if (isset($field_info['location'])) {
    $field_info['location']['property_type'] = 'field_item_location';
    $field_info['location']['property_callbacks'][] = 'location_entity_field_item_location_property_callback';
  }
}

/**
 * Property callback for location field.
 */
function location_entity_field_item_location_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = & $info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';

  foreach (location_entity_key_map() as $key => $item) {
    $property['property info'][$key] = array(
      'type' => $item['type'],
      'label' => $item['label'],
      'getter callback' => 'location_entity_field_verbatim_get',
    );
  }
}

/**
 * Gets the data from field array.
 */
function location_entity_field_verbatim_get($item, array $options, $name, $entity_type) {
  if (isset($item[$name]) && !empty($item[$name])) {
    return $item[$name];
  }

  return NULL;
}


/**
 * Helper function that returns location key map array.
 */
function location_entity_key_map() {
  return array(
    'lid' => array('type' => 'integer', 'label' => t('Lid')),
    'latitude' => array('type' => 'decimal', 'label' => t('Latitude')),
    'longitude' => array('type' => 'decimal', 'label' => t('Longitude')),
    'name' => array('type' => 'text', 'label' => t('Name')),
    'street' => array('type' => 'text', 'label' => t('Street')),
    'additional' => array('type' => 'text', 'label' => t('Additional')),
    'city' => array('type' => 'text', 'label' => t('City')),
    'province' => array('type' => 'text', 'label' => t('Province')),
    'postal_code' => array('type' => 'text', 'label' => t('Postal code')),
    'country' => array('type' => 'text', 'label' => t('Country')),
    'province_name' => array('type' => 'text', 'label' => t('Province name')),
    'country_name' => array('type' => 'text', 'label' => t('Country name')),
    'phone' => array('type' => 'text', 'label' => t('Phone number')),
    'fax' => array('type' => 'text', 'label' => t('Fax number')),
    'email' => array('type' => 'text', 'label' => t('Email')),
    'www' => array('type' => 'text', 'label' => t('Website')),
  );
}
