<?php

/**
 * @file
 * This is a 'source module' that adds a data source for the Location Taoxnomize
 * module. It implements the Location Taxonomize functionality for the 
 * Location module.
 */

require_once('location_taxonomize_location.inc');

/**
 * Register this module as a source module for Location Taxonomize
 */
function location_taxonomize_location_location_taxonomize_source() {
  return array(
   'location_taxonomize_location' => 'Location', 
  );
}

/** 
 * Implements hook_form_alter().
 */
function location_taxonomize_form_alter(&$form, &$form_state, $form_id) {
  // check if there is a location fieldset on this form
  if (isset($form['locations']) && $form['#node_edit_form'] == TRUE) {
    // add a submit handler to the form
    $form['#submit'][] = 'location_taxonomize_location_submitt';
  }
}

/**
 * Submit handler for forms with Location fields in them
 */
function location_taxonomize_location_submitt($form, &$form_state) {
  // check if this module is enabled as the current source
  if (_location_taxonomize_get_source() != LT_LOC_MODULE_ID) return;
  // check if taxonomization is enabled
  if (!location_taxonomize_enabled()) return;
  // get the location values from the form
  $locations = $form_state['values']['locations'];
  // taxonomize locations
  $items = array();
  foreach ($locations as $obj) {
    unset($obj['location_settings']);
    // skip empty locations 
    if (!location_taxonomize_location_location_empty($obj)) {
      $location = location_taxonomize_location_fixup($obj);
      $items[] = $location;
    }
  }
  if (!empty($items)) {
    location_taxonomize_taxonomize($items, $form, $form_state);
  }
}

/**
 * Runs the bulk taxonomize operation
 */
function location_taxonomize_location_bulk_taxonomize_op($form_state, &$context) {
  // initialize progress, max, and current if this is the first iteration
  if (!isset($context['sandbox']['progress'])) {
    $max = db_query('SELECT COUNT(DISTINCT lid) FROM {location}')->fetchField();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = $max;
    $context['sandbox']['current'] = 0;
    $context['results']['added'] = 0;
    $context['results']['processed'] = 0;
  }
  // maximum 20 locations per function iteration
  $limit = 20;
  // iterate through the next group of locations
  $result = db_query_range("SELECT lid, name, street, additional, city, province, postal_code, country, latitude, longitude, source FROM {location} WHERE lid <> 0 ORDER BY lid ASC", $context['sandbox']['current'], $limit, array());
  $result_array = $result->fetchAllAssoc('lid');
  $taxonomize = array();
  $count = 0;
  foreach ($result_array as $row) {
    $address = location_taxonomize_location_fixup((array)$row);
    $lid = $address['lid'];
    $nid_results = db_query("SELECT nid FROM {location_instance} WHERE lid = :lid", array(":lid" => $lid));
    $nid = $nid_results->fetchField();
    $taxonomize[$nid][] = $address;
    $count++;
  }
  $results = location_taxonomize_taxonomize_bulk($taxonomize);
  $saved = $results['saved'];
  $context['results']['added'] += $saved;
  $context['sandbox']['progress'] += $count;
  $context['message'] = t('Processing location', array());
  $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  $context['sandbox']['current'] = $context['sandbox']['progress'];
  $context['results']['processed'] = $context['sandbox']['progress'];
}

/**
 * Helper function to determine if a location object is empty or not. This is not
 * a great solution, but it's the best I can do at the moment.
 */
function location_taxonomize_location_location_empty($location) {
  $count = count($location);
  $empty = 0;
  foreach ($location as $item => $value) {
    if (empty($value) || $value == '' || !isset($value)) {
      $empty++;
    }
  }
  if ($empty >= $count - 1) return TRUE;
  else return FALSE;
}