<?php

/**
 * @file
 * Set up the migration baseball example module.
 */

function migrate_example_baseball_enable() {
  $path = dirname(__FILE__) . '/data';
  migrate_example_baseball_get_files($path);
  for ($i=0; $i<=9; $i++) {
    $file = 'GL200' . $i . '.TXT';
    Migration::registerMigration('GameBaseball',
      pathinfo($file, PATHINFO_FILENAME),
      array('source_file' => $path . '/' . $file, 'group_name' => 'baseball'));
  }
}

/**
 * Obtain our sample data from Retrosheet.
 *
 * @param $path
 */
function migrate_example_baseball_get_files($path) {
  // Don't replace old upper-case names
  if (!file_exists("$path/GL2000.TXT") && !file_exists("$path/gl2000.txt")) {
    file_prepare_directory($path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    $result = copy('http://www.retrosheet.org/gamelogs/gl2000_09.zip',
                   $path . '/gl2000_09.zip');
    if ($result) {
      $zip = new ZipArchive();
      $zip->open($path . '/gl2000_09.zip');
      $zip->extractTo($path);
      $zip->close();
      unlink("$path/gl2000_09.zip");
    }
  }
}

function migrate_example_baseball_uninstall() {
  $bundle = 'migrate_example_baseball';
  $field_names = array('field_park', 'field_home_team', 'field_home_game_number',
    'field_home_score', 'field_visiting_score', 'field_outs', 'field_attendance',
    'field_duration', 'field_home_batters', 'field_visiting_batters',
    'field_home_pitcher', 'field_visiting_pitcher', 'field_visiting_team',
    'field_start_date');
  foreach ($field_names as $field_name) {
    $instance = field_info_instance('node', $field_name, $bundle);
    field_delete_instance($instance);
    field_delete_field($field_name);
  }
  node_type_delete($bundle);
}

function migrate_example_baseball_disable() {
  MigrateGroup::deregister('baseball');
}

/**
 * Get a copy of the sample CSV data if necessary.
 */
function migrate_example_baseball_update_7201() {
  migrate_example_baseball_get_files(dirname(__FILE__) . '/data');
}
