<?php
/**
 * @version		$Id: record.php 122 2009-06-19 08:56:53Z 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;

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

/**
 * About Page Model
 *
 * @package		TAOJ.Quanta
 * @subpackage	com_quanta
 */
class QuantaModelRecord extends JxModelItem
{
	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param	string	The table name. Optional.
	 * @param	string	The class prefix. Optional.
	 * @return	object	The table
	 */
	public function &getTable($name='Record', $prefix='QuantaTable')
	{
		return JTable::getInstance($name, $prefix);
	}

	/**
	 */
	public function _populateState()
	{
		$app	= &JFactory::getApplication();

		// Load the object state.
		$id	= (int) $app->getUserState('com_quanta.edit.record.id');
		$this->setState('record.id', $id);

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

	/**
	 * Method to checkin a row.
	 *
	 * @access	public
	 * @param	integer	$id		The numeric id of a row
	 * @return	boolean	True on success/false on failure
	 */
	public function checkin($id = null)
	{
		// Initialize variables.
		$id = (int) $id;

		if ($id === 0) {
			$id = $this->getState('record.id');
		}

		if (!$id) {
			return true;
		}

		$table = $this->getTable();

		// Attempt to check-in the row.
		$return = $table->checkin($id);

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

		return true;
	}

	/**
	 * Method to check-out a object for editing.
	 *
	 * @access	public
	 * @param	int		$id	The numeric id of the object to check-out.
	 * @return	bool	False on failure or error, success otherwise.
	 */
	public function checkout($id)
	{
		// Initialize variables.
		$userId	= (int) JFactory::getUser()->get('id');
		$id		= (int) $id;

		// Check for a new object id.
		if (empty($id)) {
			return true;
		}

		$table = $this->getTable();

		// Attempt to check-out the row.
		$return = $table->checkout($userId, $id);

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

		// Check if the row is checked-out by someone else.
		if ($return === null) {
			$this->setError(JText::_('Notes_Note_checked_out'));
			return false;
		}

		return true;
	}

	/**
	 * Method to get an ojbect.
	 *
	 * @access	public
	 * @param	integer	The id of the object to get.
	 * @return	mixed	Object on success, false on failure.
	 */
	public function &getItem($id = null)
	{
		// Initialize variables.
		$id = (!empty($id)) ? $id : (int)$this->getState('record.id');

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

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

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

		// Convert the JTable to a clean JObject.
		$result = JArrayHelper::toObject($table->getProperties(1), 'JObject');
		$result->params = new JParameter(null);
		$result->params->loadArray((array) json_decode($table->params, true));

		return $result;
	}

	/**
	 * Method to get the form object.
	 *
	 * @access	public
	 * @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)
	{
		$id		= (!empty($data['id'])) ? $data['id'] : (int) $this->getState('record.id');
		$isNew	= true;

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

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

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

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

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

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

		// Now record the history

		if (intval($table->latest_time))
		{
			// Check if this record exists
			$this->_db->setQuery(
				'SELECT MAX(record_time)' .
				' FROM #__taoj_quanta_history' .
				' WHERE record_id = '.(int) $table->id
			);

			if ($maxTime = $this->_db->loadResult())
			{
				// Check if this record exists
				$this->_db->setQuery(
					'SELECT id' .
					' FROM #__taoj_quanta_history' .
					' WHERE record_id = '.(int) $table->id .
					'  AND '.$this->_db->quote($table->latest_time).' = '.$this->_db->quote($maxTime)
				);
				$recordId = $this->_db->loadResult();

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

			$history = &$this->getTable('History');
			if (empty($recordId))
			{
				$history->record_id		= (int) $table->id;
				$history->record_time	= $table->latest_time;
				$history->record_value	= $table->latest_value;
			}
			else {
				$history->load($recordId);
				$history->record_value = $table->latest_value;
			}

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

			// Store the data.
			if (!$history->store()) {
				$this->setError($history->getError());
				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($ids)
	{
		// Sanitize the ids.
		$ids = (array) $ids;
		JArrayHelper::toInteger($ids);

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

		// Iterate the items to delete each one.
		foreach ($ids as $id) {
			$table->delete($id);
		}

		return true;
	}

	/**
	 * Method to change the publish state of an item
	 *
	 * @param	array	$ids	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($ids, $value = 1)
	{
		$table	= &$this->getTable();

		if (!$table->publish($ids, $value, JFactory::getUser()->get('id'))) {
			$this->setError($table->getError());
			return false;
		}
		return true;
	}
}