<?php
// $Id: regions_api.module,v 1.1.2.1 2009/05/17 10:43:14 mrfelton Exp $

/**
 * @file
 * Regions API provides an API for accessing country region (province/state)
 * data.
 */

/**
 * Implementation of hook_help().
 */
function regions_api_help($path, $arg) {
  switch ($path) {
    case 'admin/help#regions_api':
      return '<p>'. t('Help Section Coming Soon.') .'</p>';
  }
}

/**
 * Function to get a region by iso2 country name
 * @param $iso2 
 *  A string corresponding to a regions ISO2 name.
 * @return array|null
 *  Returns an array of regions or NULL if no results found
**/
function regions_api_iso2_get_array($iso2) {
  $result = db_query("SELECT rid, iso2, name, abbreviation FROM {regions_api_regions} WHERE iso2 = '%s'", $iso2);
  $regions = array();
  while ($row = db_fetch_array($result)) {
    $regions[] = $row;
  }
  if (count($regions) == 0) {
    return NULL;
  }
  return $regions;
}

/**
 * Funtion to get an options array of country regions
 * @param $iso2 
 *  A string corresponding to a regions ISO2 name.
**/
function regions_api_iso2_get_options_array($iso2) {
 $result = db_query("SELECT name, abbreviation FROM {regions_api_regions} WHERE iso2 = '%s'", $iso2);
 $regions = array();
  while ($row = db_fetch_array($result)) {
    $key = (strlen($row['abbreviation']) > 0) ? $row['abbreviation'] : $row['name'];
    $value = $row['name'];
    $regions[$key] = $value;
  }
  if (count($regions) == 0) {
    return NULL;
  }
  return $regions;
}

/**
* Function to import regions from CSV file
* TODO: provide arguments for specifying csv files
* TODO: Setup permissions
* @param $offset
*   Int value for csv row offset.
**/
function regions_api_csv_import_regions($offset=1) {
  //Prepopulate regions table
  $handle = fopen(dirname(__FILE__) ."/data/regions.csv", "r");
  $index = 1;
  while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
    //Create row variables
    $iso2 = ($row[0]) ? $row[0] : "";
    $name = ($row[1]) ? $row[1] : "";
    $abbreviation = ($row[2]) ? $row[2] : "";
    if ($index > $offset) {
      db_query(
          "INSERT INTO {regions_api_regions} (iso2, name, abbreviation) VALUES('%s', '%s', '%s')",
           $iso2, $name, $abbreviation
      );
    }
    $index++;
  }
  fclose($handle);
  watchdog('regions_api', "Pre-populated regions data.");
}