<?php
/**
 * @version		$Id: import.php 134 2009-06-24 05:52:18Z eddieajau $
 * @copyright	Copyright (C) 2009 New Life in IT Pty Ltd. All rights reserved.
 * @license		GNU General Public License <http://www.gnu.org/copyleft/gpl.html>
 * @link		http://www.theartofjoomla.com
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.model');

/**
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class QuantaModelImport extends JModel
{
	function upload()
	{
		$file			= $this->getState('src_file');
		$dateColumn		= $this->getState('date_column');
		$valueColumn	= $this->getState('value_column');
		$recordId		= (int) $this->getState('record_id');

		$tuples	= array();
		if (isset($file['tmp_name']))
		{
			$delimiter	= $this->getState('import.delimiter');
			$enclosure	= $this->getState('import.enclosure');
			$handle		= fopen($file['tmp_name'], 'r');

			// Get first line in the file (which contains the column names) as an array.
			// TODO: Add option to ignore first line.
				if ($enclosure) {
					$fields = fgetcsv($handle, 0, $delimiter, $enclosure);
				}
				else {
					$fields = fgetcsv($handle, 0, $delimiter);
				}

				// Compute the column numbers.
			if (!is_numeric($dateColumn))
			{
				$dateColumn = array_search($dateColumn, $fields);
				if ($dateColumn === false)
				{
					$this->setError('Quanta_Error_Date_column_not_found');
					return false;
				}
			}
			else {
				$dateColumn--;
			}

			if (!is_numeric($valueColumn))
			{
				$valueColumn = array_search($valueColumn, $fields);
				if ($valueColumn === false)
				{
					$this->setError('Quanta_Error_Value_column_not_found');
					return false;
				}
			}
			else {
				$valueColumn--;
			}

			$db = &$this->_db;

			// Create a reverse lookup for the existing records.
			$db->setQuery(
				'SELECT id, record_time' .
				' FROM #__taoj_quanta_history' .
				' WHERE record_id = '.$recordId
			);
			$lookup = $db->loadObjectList('record_time');

			jimport('joomla.utilities.date');
			$app	= &JFactory::getApplication();
			$offset	= $app->getCfg('offset');

			while (($values = ($enclosure ? fgetcsv($handle, 0, $delimiter, $enclosure) : fgetcsv($handle, 0, $delimiter))) !== FALSE)
			{
				$date	= $values[$dateColumn];
				$value	= (double) $values[$valueColumn];

				// Check that the date looks valid.
				if (intval($date))
				{
					$time	= new JDate($values[$dateColumn], $offset);
					$date	= $time->toMySQL();

					$id = isset($lookup[$date]) ? (int) $lookup[$date]->id : 0;
					$tuples[] = '('.$id.','.$recordId.','.(double) $value.','.$db->quote($date).')';
				}
			}
			fclose($handle);

			// Do the inserts in batches of max 1000.
			$n		= count($tuples);
			$limit	= 1000;
			for ($i = 0; $i < $n; $i += $limit)
			{
				$slice = array_slice($tuples, $i, $limit);
				$db->setQuery(
					'REPLACE INTO #__taoj_quanta_history (id, record_id, record_value, record_time)' .
					' VALUES '.implode(',', $slice)
				);
				if (!$db->query())
				{
					$this->setError($db->getErrorMsg());
					return false;
				}
			}
		}

		// Update the latest value.
		$model = &JModel::setInstance('History', 'QuantaModel');
		if (!$model->updateLatest($recordId)) {
			$this->setError($model->getError());
			return false;
		}

		return true;
	}
}