<?php
/**
 * 改造后的CWebUser，不使用session来保持登录状态
 */
class CommonUser extends CWebUser
{
	private $_uid;
	
	private $_username;
	
	private $_iorange;
	
	const COMMON_STATE_KEY = 'CommonUserState';
	
	public function init()
	{
		$this->setStateKeyPrefix('iOrangeCookiePrefix');
		//$this->updateFlash();
	}
	
	public function __get($name)
	{
		if($this->hasState($name))
		{
			return $this->getState($name);
		}
		else
		{
			return parent::__get($name);
		}
	}
	
	public function __set($name,$value)
	{
		if($this->hasState($name))
		{
			$this->setState($name,$value);
		}
		else
		{
			parent::__set($name,$value);
		}
	}
	
	public function __unset($name)
	{
		if($this->hasState($name))
		{
			$this->setState($name,null);
		}
		else
		{
			parent::__unset($name);
		}
	}

	public function __isset($name)
	{
		if($this->hasState($name))
		{
			return $this->getState($name)!==null;
		}
		else
		{
			return parent::__isset($name);
		}
	}
	
	public function login($identity)
	{
		$this->changeIdentity($identity->getId(),$identity->getName(),$identity->getPersistentStates());
		$cookie = new CHttpCookie('iOrangeUser', '');
		$cookie->value = iTool::strCode(Yii::app()->user->id . "\t" . Yii::app()->user->name . "\t" . Yii::app()->user->password . "\t" . $identity->getMobile());
		Yii::app()->getRequest()->getCookies()->add($cookie->name, $cookie);
	}
	
	public function logout()
	{
		$this->clearStates();
		Yii::app()->getRequest()->getCookies()->remove('iOrangeUser');
	}
	
	/**
	 * 从cookie里恢复登录状态
	 * @return void
	 */
	protected function restoreFromCookie()
	{
		
	}

	public function getState($key, $defaultValue = null)
	{
		$key = $this->getStateKeyPrefix() . $key;
		//$value = Yii::app()->getParams($key);
		$params = Yii::app()->getParams();
		$states = $params[self::COMMON_STATE_KEY];

		return isset($states[$key]) ? $states[$key] : $defaultValue;
	}
	
	public function setState($key, $value)
	{
		$key = $this->getStateKeyPrefix() . $key;
		$params = Yii::app()->getParams();
		$states = isset($params[self::COMMON_STATE_KEY]) ? $params[self::COMMON_STATE_KEY] : array();
		$states[$key] = $value;
		$params[self::COMMON_STATE_KEY] = $states;
	}
	
	public function hasState($key)
	{
		$key = $this->getStateKeyPrefix() . $key;
		$params = Yii::app()->getParams();
		$states = $params[self::COMMON_STATE_KEY];
		
		return !empty($states[$key]);
	}
	
	public function clearStates()
	{
		Yii::app()->setParams(array(self::COMMON_STATE_KEY=>array()));
	}
	
	protected function changeIdentity($id, $name, $states)
	{
		parent::setId($id);
		parent::setName($name);
		$this->loadIdentityStates($states);
	}
	
	protected function loadIdentityStates($states)
	{
		$names = array();
		if(is_array($states))
		{
			foreach($states as $name => $value)
			{
				$this->setState($name, $value);
				$names[$name] = true;
			}
		}
		$this->setState(self::STATES_VAR,$names);
	}
}
?>