<?php

class MigrateTextAuthorFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('textauthor'));
  }

  static function arguments($author = NULL, $format = NULL, $language = NULL) {
    $arguments = array();
    if (!is_null($author)) {
      $arguments['author'] = $author;
   }
    if (!is_null($format)) {
      $arguments['format'] = $format;
    }
    if (!is_null($language)) {
      $arguments['language'] = $language;
    }
    return $arguments;
  }

  public function fields($type) {
    $fields = array();
    $fields = array(
      'author' => t('Subfield: Text author'),
      'format' => t('Subfield: Text format for the field'),
      'language' => t('Subfield: Language for the field'),
    );
    return $fields;
  }

  public function prepare($entity, array $field_info, array $instance, array $values) {
    if (isset($values['arguments'])) {
      $arguments = $values['arguments'];
      unset($values['arguments']);
    }
    else {
      $arguments = array();
    }

    $migration = Migration::currentMigration();
    $destination = $migration->getDestination();
    $language = $this->getFieldLanguage($entity, $field_info, $arguments);
    $max_length = isset($field_info['settings']['max_length']) ?
      $field_info['settings']['max_length'] : 0;

    // Setup the standard Field API array for saving.
    $delta = 0;
    foreach ($values as $value) {
      $item = array();
      if (isset($arguments['author'])) {
        if (is_array($arguments['author'])) {
          $item['author'] = $arguments['author'][$delta];
        }
        else {
          $item['author'] = $arguments['author'];
        }
      }
      if (isset($arguments['format'])) {
        if (is_array($arguments['format'])) {
          $format = $arguments['format'][$delta];
        }
        else {
          $format = $arguments['format'];
        }
      }
      else {
        $format = $destination->getTextFormat();
      }
      $item['format'] = $item['value_format'] = $format;
      // Make sure the value will fit
      if ($max_length) {
        $item['value'] = drupal_substr($value, 0, $max_length);
        if (!empty($arguments['track_overflow'])) {
          $value_length = drupal_strlen($value);
          if ($value_length > $max_length) {
            $migration->saveMessage(
              t('Value for field !field exceeds max length of !max_length, actual length is !length',
                array('!field' => $instance['field_name'], '!max_length' => $max_length,
                  '!length' => $value_length)),
              Migration::MESSAGE_INFORMATIONAL);
          }
        }
      }
      else {
        $item['value'] = $value;
      }

      if (is_array($language)) {
        $current_language = $language[$delta];
      }
      else {
        $current_language = $language;
      }
      $return[$current_language][] = $item;
      $delta++;
    }

    return isset($return) ? $return : NULL;
  }
}
