<?php
/**
 * @version		$Id$
 * @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;

jximport('jxtended.application.component.modelitem');

/**
 * About Page Model
 *
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class QuantaModelHistory extends JxModelItem
{
	/**
	 * Returns a reference to the a Table object, always creating it
	 *
	 * @param	type 	$type 	 The table type to instantiate
	 * @param	string 	$prefix	 A prefix for the table class name. Optional.
	 * @param	array	$options Configuration array for model. Optional.
	 * @return	JTable	A database object
	*/
	public function &getTable($type = 'History', $prefix = 'QuantaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Auto-populate the model state.
	 *
	 * @return	void
	 */
	public function _populateState()
	{
		$app = &JFactory::getApplication('administrator');

		// Load the User state.
		if (!($pk = (int) $app->getUserState('com_quanta.edit.history.id'))) {
			$pk = (int) JRequest::getInt('history_id');
		}
		$this->setState('history.id', $pk);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_quanta');
		$this->setState('params', $params);
	}

	/**
	 * Method to get a row.
	 *
	 * @param	integer	An optional id of the object to get, otherwise the id from the model state is used.
	 *
	 * @return	mixed	Object on success, false on failure.
	 */
	public function &getItem($pk = null)
	{
		// Initialize variables.
		$pk = (!empty($pk)) ? $pk : (int)$this->getState('history.id');

		// Get a level row instance.
		$table = &$this->getTable();

		// Attempt to load the row.
		$table->load($pk);

		// Check for a table object error.
		if ($error = $table->getError())
		{
			$this->setError($error);
			$false = false;
			return $false;
		}

		// Convert the params field to an array.
		//$registry = new JRegistry();
		//$registry->loadJSON($table->params);
		//$table->params = $registry->toArray();

		// Convert the JTable to a clean JObject.
		$result = JArrayHelper::toObject($table->getProperties(1), 'JObject');

		return $result;
	}

	/**
	 * Method to get the form object.
	 *
	 * @param	string	$type	The type of form to load (view, model);
	 * @return	mixed	JXForm object on success, false on failure.
	 */
	public function &getForm($type = 'view')
	{
		jximport('jxtended.form.helper');
		JXFormHelper::addIncludePath(JPATH_COMPONENT.DS.'models');

		if ($type == 'model') {
			$result = &JXFormHelper::getModel($this->getName());
		}
		else {
			$result = &JXFormHelper::getView($this->getName());
		}

		if (JError::isError($result)) {
			$this->setError($result->message);
			return false;
		}

		return $result;
	}

	/**
	 * Method to save the form data.
	 *
	 * @access	public
	 * @param	array	The form data.
	 * @return	boolean	True on success.
	 */
	public function save($data)
	{
		$pk		= (!empty($data['id'])) ? $data['id'] : (int) $this->getState('history.id');
		$isNew	= true;

		// Get a group row instance.
		$table = &$this->getTable();

		// Load the row if saving an existing item.
		if ($pk > 0) {
			$table->load($pk);
			$isNew = false;
		}

		// Bind the data.
		if (!$table->bind($data)) {
			$this->setError(JText::sprintf('JTable_Error_Bind_failed', $table->getError()));
			return false;
		}

		// Check the data.
		if (!$table->check()) {
			$this->setError($table->getError());
			return false;
		}

		// Store the data.
		if (!$table->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		$this->setState('history.id', $table->id);

		if (!$this->updateLatest($table->record_id)) {
			return false;
		}

		return true;
	}

	/**
	 * This method updates the record with the latest historic value.
	 *
	 * @param	int	$recordId	The ID of the record.
	 *
	 * @return	boolean			True is successful, false otherwise and an internal error is set.
	 */
	public function updateLatest($recordId)
	{
		jximport('joomla.database.query');

		$query = new JxQuery;
		$query->select('h.record_value, h.record_value2, h.record_time');
		$query->select('r.latest_value, r.latest_value2, r.latest_time');
		$query->from('#__taoj_quanta_history AS h');
		$query->join('INNER', '#__taoj_quanta_records AS r ON r.id = h.record_id');
		$query->where('h.record_id = '.(int) $recordId);
		$query->order('h.record_time DESC');

		// Find the latest historic result and the cached values in the record.
		$this->_db->setQuery((string) $query, 0, 1);
		if ($result = $this->_db->loadObject())
		{
			// If any field is different, update the cache in the record.
			if ($result->latest_time != $result->record_time || $result->latest_value != $result->record_value || $result->latest_value2 != $result->record_value2)
			{
				$this->_db->setQuery(
					'UPDATE #__taoj_quanta_records' .
					' SET latest_time = '.$this->_db->quote($result->record_time) .
					', latest_value = '.(double) $result->record_value .
					', latest_value2 = '.(double) $result->record_value2 .
					' WHERE id = '.(int) $recordId
				);
				if (!$this->_db->query()) {
					$this->setError($this->_db->getError());
					return false;
				}
			}
		}

		if ($error = $this->_db->getErrorMsg()) {
			$this->setError($error);
			return false;
		}

		return true;
	}

	/**
	 * Method to delete groups.
	 *
	 * @access	public
	 * @param	array	An array of group ids.
	 * @return	boolean	Returns true on success, false on failure.
	 */
	public function delete($pks)
	{
		$pks = (array) $pks;

		// Get a row instance.
		$table = &$this->getTable();

		// Iterate the items to delete each one.
		foreach ($pks as $pk)
		{
			if (!$table->delete((int) $pk))
			{
				$this->setError($table->getError());
				return false;
			}
		}

		return true;
	}

	/**
	 * Method to change the published state of an item
	 *
	 * @param	array	$pks	The IDs of the taxonomy rows to publish.
	 * @param	int		$value	The value to set
	 * @return	mixed	True on success or JExeception object on failure
	 */
	public function publish($pks, $value = 1)
	{
		$pks = (array) $pks;

		// Get the current user object.
		$user = &JFactory::getUser();

		// Get an instance of the table row.
		$table = &$this->getTable();

		// Attempt to publish the items.
		if (!$table->publish($pks, $value, $user->get('id')))
		{
			$this->setError($table->getError());
			return false;
		}

		return true;
	}
}