<?php

/**
 * Implements hook_field_schema()
 */
function addressfield_field_schema() {
  $columns = array(
    'country' => array(
      'description' => 'Two letter ISO country code of this address.',
      'type' => 'varchar',
      'length' => 2,
      'not null' => FALSE,
      'default' => '',
    ),
    'administrative_area' => array(
      'description' => 'The administrative area of this address. (i.e. State/Province)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_administrative_area' => array(
      'description' => 'The sub administrative area of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'locality' => array(
      'description' => 'The locality of this address. (i.e. City)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'dependent_locality' => array(
      'description' => 'The dependent locality of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'postal_code' => array(
      'description' => 'The postal code of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'thoroughfare' => array(
      'description' => 'The thoroughfare of this address. (i.e. Street address)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'premise' => array(
      'description' => 'The premise of this address. (i.e. Apartment / Suite number)',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'sub_premise' => array(
      'description' => 'The sub_premise of this address.',
      'type' => 'varchar',
      'length' => 255,
      'default' => '',
      'not null' => FALSE,
    ),
    'organisation_name' => array(
      'description' => 'Contents of a primary OrganisationName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'name_line' => array(
      'description' => 'Contents of a primary NameLine element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'first_name' => array(
      'description' => 'Contents of the FirstName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'last_name' => array(
      'description' => 'Contents of the LastName element of a primary PersonName element in the xNL XML.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => FALSE,
      'default' => '',
    ),
    'data' => array(
      'description' => 'Additional data for this address.',
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
      'serialize' => TRUE,
    ),
  );

  return array(
    'columns' => $columns,
    // TODO Add indexes.
  );
}

/**
 * Update the field configuration to the new plugin structure.
 */
function addressfield_update_7000() {
  // Enable ctools.
  if (!module_enable(array('ctools'))) {
    throw new Exception('This version of addressfield requires ctools, but it could not be enabled.');
  }

  // Get the list of fields of type 'addressfield'.
  $address_fields = array();
  foreach (field_info_fields() as $field_name => $field_info) {
    if ($field_info['type'] == 'addressfield') {
      $address_fields[$field_name] = $field_name;
    }
  }

  foreach (field_info_instances() as $entity_type => $bundles) {
    foreach ($bundles as $bundle_name => $instances) {
      foreach (array_intersect_key($instances, $address_fields) as $field_name => $instance) {
        $widget_settings = &$instance['widget']['settings'];

        if ($instance['widget']['type'] == 'addressfield_standard') {
          // Default to use the country-based address widget.
          $format_handlers = array('address');

          // Map the old 'name_format' setting to the name and organization widgets.
          if (in_array($widget_settings['name_format'], array('name_line_organisation', 'first_last_organisation'))) {
            $format_handlers[] = 'organisation';
          }
          if (in_array($widget_settings['name_format'], array('name_line', 'name_line_organisation'))) {
            $format_handlers[] = 'name-oneline';
          }
          else {
            $format_handlers[] = 'name-full';
          }
          unset($widget_settings['name_format']);
          $widget_settings['format_handlers'] = $format_handlers;
        }

        // Update displays.
        foreach ($instance['display'] as $view_mode => &$view_mode_info) {
          $display_settings = &$view_mode_info['settings'];

          if ($view_mode_info['type'] == 'addressfield_default') {
            if (isset($widget_settings['format_handlers'])) {
              $display_settings['use_widget_handlers'] = 1;
            }
            else {
              // If the widget is non-standard, just use a sane default.
              $display_settings['use_widget_handlers'] = 0;
              $display_settings['format_handlers'] = array('address', 'name-oneline');
            }
          }
          else if ($view_mode_info['type'] == 'addressfield_name') {
            // Migrate the 'addressfield_name' formatter to the new framework.
            $view_mode_info['type'] = 'addressfield_default';
            // Start from the widget configuration.
            $display_settings['use_widget_handlers'] = 0;
            $display_settings['format_handlers'] = isset($widget_settings['format_handlers']) ? $widget_settings['format_handlers'] : array('address', 'name-oneline');

            if (empty($display_settings['organisation'])) {
              $display_settings['format_handlers'] = array_diff( $display_settings['format_handlers'], array('organisation'));
            }
            unset($display_settings['organisation']);
          }
        }

        field_update_instance($instance);
      }
    }
  }
}

/**
 * Sets the value of the new "Default country" setting.
 */
function addressfield_update_7001() {
  $address_fields = array();
  foreach (field_info_fields() as $field_name => $field_info) {
    if ($field_info['type'] == 'addressfield') {
      $address_fields[$field_name] = $field_name;
    }
  }

  foreach (field_info_instances() as $entity_type => $bundles) {
    foreach ($bundles as $bundle_name => $instances) {
      foreach (array_intersect_key($instances, $address_fields) as $field_name => $instance) {
        // Optional fields get the None default. Required fields get the
        // previously selected default country.
        $default_country = '';
        if (!empty($instance['required']) && !empty($instance['default_value'])) {
          $default_country = $instance['default_value'][0]['country'];
        }

        $instance['widget']['settings']['default_country'] = $default_country;
        unset($instance['default_value']);

        field_update_instance($instance);
      }
    }
  }
}
