<?php

define('ENTITY_TRANSLATION_SEARCH_API_NO_TRANSLATION', 'none');

/**
 * Implements hook_search_api_search_api_item_type_info_alter().
 */
function entity_translation_search_api_search_api_item_type_info_alter(array &$infos) {
  foreach ($infos as $type => $info) {
    if (entity_get_info($type)) {
      $infos[$type]['datasource controller'] = 'EntityTranslationDataSourceController';
    }
  }
}

/**
 * Implements hook_form_alter().
 */
function entity_translation_search_api_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, array(
    'search_api_admin_add_index',
    'search_api_admin_index_edit',
  ))) {
    if ($form_id == 'search_api_admin_index_edit') {
      $index = $form_state['index'];
      $default = isset($index->options['entity_translation_language']) ? $index->options['entity_translation_language'] : ENTITY_TRANSLATION_SEARCH_API_NO_TRANSLATION;
    }
    else {
      $default = ENTITY_TRANSLATION_SEARCH_API_NO_TRANSLATION;
    }
    $languages = language_list('enabled');
    $languages = $languages[1];
    $names = array(ENTITY_TRANSLATION_SEARCH_API_NO_TRANSLATION => t('No translation'));
    foreach ($languages as $langcode => $item) {
      $name = t($item->name);
      $names[$langcode] = $name . ($item->native != $name ? ' (' . $item->native . ')' : '');
    }
    $form['options']['entity_translation_language'] = array(
      '#type' => (count($names) <= 5 ? 'radios' : 'select'),
      '#title' => t('Entity translation language'),
      '#description' => t('To which language the entities should be translated before indexing.'),
      '#default_value' => $default,
      '#options' => $names,
    );
  }
}

/**
 * Implements hook_search_api_index_items_alter().
 * For compatibility with language control data alteration.
 */
function entity_translation_search_api_search_api_index_items_alter(array &$items, SearchApiIndex $index) {
  $target_language = $index->options['entity_translation_language'];
  if ($target_language != ENTITY_TRANSLATION_SEARCH_API_NO_TRANSLATION) {
    foreach ($items as $id => $item) {
      if (isset($item->translations->data[$target_language])) {
        $item->language = $target_language;
      }
    }
  }
}
