<?php

/**
 * Implementation of hook_features_api().
 */
function features_translations_features_api() {
  return array(
    'translations' => array(
      'name' => t('Translations'),
      'default_hook' => 'translations_defaults',
      'feature_source' => TRUE,
      'default_file' => FEATURES_DEFAULTS_INCLUDED,
    ),
  );
}

/**
 * Implementation of hook_features_export_options().
 */
function translations_features_export_options() {
  $options = array();
  $textgroups = module_invoke_all('locale', 'groups');
  foreach (language_list() as $langcode => $language) {
    if ($langcode == translations_features_string_source_language()) continue;
    foreach ($textgroups as $textgroup => $label) {
      $options[$langcode . ':' . $textgroup] = t($language->name) . ': ' . $label;
    }
  }
  return $options;
}

/**
 * Helper to return site's string source language.
 */
function translations_features_string_source_language() {
  if (module_exists('i18n_string')) {
    return i18n_string_source_language();
  }
  return language_default('language');
}

/**
 * Implementation of hook_features_export().
 */
function translations_features_export($data, &$export, $module_name) {
  $export['features']['translations'] = array_combine(array_values($data), array_values($data));
  $export['dependencies']['features'] = 'features';
  return array();
}

/**
 * Implementation of hook_features_export_render().
 */
function translations_features_export_render($module_name, $data, $export = NULL) {
  $languages = language_list();
  $code = array();
  $code[] = '  $translations = array();';
  foreach ($data as $component) {
    list($langcode, $textgroup) = explode(':', $component);
    $strings = _features_translations_locale_export_get_strings($languages[$langcode], $textgroup);
    foreach ($strings as $md5 => $string) {
      $code[] = "  \$translations['{$langcode}:{$textgroup}']['{$md5}'] = " . features_var_export($string, '  ') . ";";
    }
  }
  $code[] = '  return $translations;';
  $code = implode("\n", $code);
  return array('translations_defaults' => $code);
}

/**
 * Implementation of hook_features_revert().
 */
function translations_features_revert($module_name) {
  include_once('includes/locale.inc');
  $translations = features_get_default('translations', $module_name);
  if (!empty($translations)) {
    $report = array();
    $lids = array();
    foreach ($translations as $key => $strings) {
      list($langcode, $textgroup) = explode(':', $key);
      foreach ($strings as $md5 => $string) {
        if (!empty($string['plid'])) {
          if (!isset($lids[$string['plid']])) {
            watchdog('features', 'Translations: importing plid %plid not found for string %source.', array('%plid' => $string['plid'], '%source' => $string->source));
            $string['plid'] = 0;
          }
          else {
            $string['plid'] = $lids[$string['plid']];
          }
        }
        $lids[$md5] = _locale_import_one_string_db(
          $report, 
          $langcode, 
          $string['context'], 
          $string['source'], 
          $string['translation'], 
          $textgroup, 
          $string['location'], 
          LOCALE_IMPORT_OVERWRITE, 
          $string['plid'],
          $string['plural']
        );
      }
    }
  }
  return TRUE;
}

/**
 * Implementation of hook_features_export_rebuild().
 */
function translations_features_export_rebuild($module_name) {
  return translations_features_revert($module_name);
}

/**
 * Helper to return translated strings in given language and group.
 */
function _features_translations_locale_export_get_strings($language, $group) {
  $result = db_query("
    SELECT s.lid, s.source, s.context, s.location, t.translation, t.plid, t.plural 
    FROM {locales_source} s 
    INNER JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language 
    WHERE s.textgroup = :textgroup 
    ORDER BY s.lid
  ", array(':language' => $language->language, ':textgroup' => $group));
  $strings = array();
  $lids = array();
  foreach ($result as $string) {
    $md5 = md5(serialize(array($string->source, $string->context, $string->plural)));
    $lids[$string->lid] = $md5;
    if (!empty($string->plid)) {
      if (!isset($lids[$string->plid])) {
        watchdog('features', 'Translations: exporting plid %plid not found for string %source.', array('%plid' => $string->plid, '%source' => $string->source));
        $string->plid = 0;
      }
      else {
        $string->plid = $lids[$string->plid];
      }
    }
    unset($string->lid); // don't want the lid in the export
    $strings[$md5] = $string;
  }
  return $strings;
}

