<?php

class UserIdentity extends CBaseUserIdentity 
{
	private $_id;
	
	private $_mobile;
		
	private $_password;
	
	private $_name;
	
	public function __construct($mobile, $password)
	{
		$this->_mobile = $mobile;
		$this->_password = $password;
	}

	public function authenticate()
	{
		$user = Member::model()->find('mobile=:mobile', array(':mobile'=>$this->_mobile));
		if($user === null)
		{
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		else if($user->password !== $this->_password)
		{
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		}
		else
		{
			$this->setId($user->uid);
			$this->setName($user->username);
			
			$states = array('iorange'=>$user->iorange,'password'=>$user->password);
			$this->setStates($states);
			$this->errorCode = self::ERROR_NONE;
			
			$this->updateUserLastLogin($user->uid);
		}

		return !$this->errorCode;
	}
	
	public function setStates(Array $states)
	{
		if (is_array($states))
		{
			foreach ($states as $key => $states)
			{
				$this->setState($key, $states);
			}
		}
	}
	
	/**
	 * 更新用户最后登录时间与IP，同时做一些其他处理
	 * @param int $uid
	 * @return void
	 */
	public function updateUserLastLogin($uid)
	{
		$table = Member::model()->tableName();
		$time = time();
		$sql = "UPDATE {$table} SET lastip = '{$_SERVER[REMOTE_ADDR]}', lastvisit = '{$time}' WHERE uid = '$uid'";
		Yii::app()->getDb()->createCommand($sql)->execute();
	}

	public function getId()
	{
		return $this->_id;
	}
	
	public function setId($id)
	{
		$this->_id = $id;
	}
	
	public function setName($name)
	{
		$this->_name = $name;
	}
	
	public function getName()
	{
		return $this->_name;
	}
	
	public function getMobile()
	{
		return $this->_mobile;
	}
}