<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VP Framework for Joomla!
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2015 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          http://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */
defined('_JEXEC') or die;

/**
* VP Framework Global
* 
* @since 1.0.0
*/
class VPFrameworkState
{
	protected $db;
	
	protected $tbl_name;
	
	protected $states = array();
	
	protected $loaded = array();
	
	protected static $instance = null;
	
	public function __construct($options = array())
	{
		$this->db = isset($options['db']) ? $options['db'] : JFactory::getDbo();
		$this->tbl_name = '#__vpframework_states';
	}
	
	public static function getInstance($options = array())
	{
		if(self::$instance === null)
		{
			self::$instance = new VPFrameworkState($options);
		}
		
		return self::$instance;
	}
	
	public function set($name, $value)
	{
		$name  = strval($name);
		$value = strval($value);
		
		$this->states[$name] = $value;
		
		$query = $this->db->getQuery(true);
		
		$query->delete($this->db->quoteName($this->tbl_name))
		      ->where($this->db->quoteName('name') . ' = ' . $this->db->quote($name));
		
		$this->db->setQuery($query);
		$this->db->execute();
		
		// Insert columns.
		$columns = array($this->db->quoteName('name'), $this->db->quoteName('value'));
		
		// Insert values.
		$values = array($this->db->quote($name), $this->db->quote($value));
		
		$query->clear()
		      ->insert($this->db->quoteName($this->tbl_name))
		      ->columns($columns)
		      ->values(implode(',', $values));

		$this->db->setQuery($query);
		$result = $this->db->execute();
		
		return $result;
	}
	
	public function get($name, $default)
	{
		$name = strval($name);
		
		if(isset($this->states[$name]))
		{
			return $this->states[$name];
		}
		
		$value = $this->_load($name);
		
		if($value !== null)
		{
			$this->states[$name] = $value;
			
			return $value;
		}
		
		return $default;
	}
	
	protected function _load($name)
	{
		if(!isset($this->loaded[$name]))
		{
			$query = $this->db->getQuery(true);
			
			$query->select(array($this->db->quoteName('name'), $this->db->quoteName('value')))
			      ->from($this->db->quoteName($this->tbl_name))
			      ->where($this->db->quoteName('name') . ' = ' . $this->db->quote($name));
			
			$this->db->setQuery($query);
			$result = $this->db->loadObject();
			
			if($result && !empty($result->name))
			{
				$this->loaded[$name] = $result->value;
			}
			else
			{
				$this->loaded[$name] = null;
			}
		}
		
		return $this->loaded[$name];
	}
}