<?php

/**
 * @file
 * Install, update and uninstall functions for the list module.
 */

/**
 * Implements hook_field_schema().
 */
function list_field_schema($field) {
  switch ($field['type']) {
    case 'list_text':
      $columns = array(
        'value' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => FALSE,
        ),
      );
      break;
    case 'list_float':
      $columns = array(
        'value' => array(
          'type' => 'float',
          'not null' => FALSE,
        ),
      );
      break;
    case 'list_integer':
    case 'list_boolean':
      $columns = array(
        'value' => array(
          'type' => 'int',
          'not null' => FALSE,
        ),
      );
      break;
  }
  return array(
    'columns' => $columns,
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

/**
 * Rename the list field types and change 'allowed_values' format.
 */
function list_update_7001() {
  $fields = _update_7000_field_read_fields(array('module' => 'list'));
  foreach ($fields as $field) {
    $update = array();

    // Translate the old string format into the new array format.
    $allowed_values = $field['settings']['allowed_values'];
    if (is_string($allowed_values)) {
      $position_keys = ($field['type'] == 'list');
      $allowed_values = _list_update_7001_extract_allowed_values($allowed_values, $position_keys);

      // Additionally, float keys need to be disambiguated ('.5' is '0.5').
      if ($field['type'] == 'list_number' && !empty($allowed_values)) {
        $keys = array_map(create_function('$a', 'return (string) (float) $a;'), array_keys($allowed_values));
        $allowed_values = array_combine($keys, array_values($allowed_values));
      }

      // Place the new setting in the existing serialized 'data' column.
      $data = db_query("SELECT data FROM {field_config} WHERE id = :id", array(':id' => $field['id']))->fetchField();
      $data = unserialize($data);
      $data['settings']['allowed_values'] = $allowed_values;
      $update['data'] = serialize($data);
    }

    // Rename field types.
    $types = array('list' => 'list_integer', 'list_number' => 'list_float');
    if (isset($types[$field['type']])) {
      $update['type'] = $types[$field['type']];
    }

    // Save the new data.
    if ($update) {
      $query = db_update('field_config')
        ->condition('id', $field['id'])
        ->fields($update)
        ->execute();
    }
  }
}

/**
 * Helper function for list_update_7001: extract allowed values from a string.
 *
 * This reproduces the parsing logic in use before D7 RC2.
 */
function _list_update_7001_extract_allowed_values($string, $position_keys) {
  $values = array();

  $list = explode("\n", $string);
  $list = array_map('trim', $list);
  $list = array_filter($list, 'strlen');

  foreach ($list as $key => $value) {
    // Check for a manually specified key.
    if (strpos($value, '|') !== FALSE) {
      list($key, $value) = explode('|', $value);
    }
    // Otherwise see if we need to use the value as the key. The "list" type
    // will automatically convert non-keyed lines to integers.
    elseif (!$position_keys) {
      $key = $value;
    }
    $values[$key] = (isset($value) && $value !== '') ? $value : $key;
  }

  return $values;
}

/**
 * @addtogroup updates-7.x-extra
 * @{
 */

/**
 * Re-apply list_update_7001() for deleted fields.
 */
function list_update_7002() {
  // See http://drupal.org/node/1022924: list_update_7001() intitally
  // overlooked deleted fields, which then caused fatal errors when the fields
  // were being purged.
  // list_update_7001() has the required checks to ensure it is reentrant, so
  // it can simply be executed once more..
  list_update_7001();
}

/**
 * @} End of "addtogroup updates-7.x-extra".
 */
