<?php
class accountProxy{
	/**
	 * 添加一个代理帐号
	 */
	function add($data) {
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);
		$db->setIgnoreInsert(true);
		$rs = $db->save($data);
		return RST($rs);
	}
	
	/**
	 * 修改
	 * @param array $data
	 * @param string $id
	 */
	function edit($data, $sina_uid) {
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);		
		return RST($db->save($data, $sina_uid, '', 'sina_uid'));
	}
	

	/**
	 * 得到帐号列表
	 */
	function getList() {
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);
		$rs = $db->query('SELECT * FROM '. $db->getTable(T_ACCOUNT_PROXY));
		return RST($rs);
	}

	/**
	 * 删除帐号
	 */
	function delAccount($id) {
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);
		$rs = $db->delete($id);
		return RST($rs);
	}

	/**
	 * 判断是否已经设置代理帐号
	 */
	function issetProxy() {
		$count = $this->getCount();
		$rs = ($count['rst'] > 0) ? true : false;
		return RST($rs);
	}

	/**
	 * 得到随机帐号
	 */
	function getRandomAccount($useMem = true) {
		if(true == $useMem){
			return $this->_getRandomAccountInMem();
		}
		
		$rows = $this->getList();
		$count = count($rows['rst']);
		if ($count < 1) {
			return RST(false);
		}
		$rand = rand(0, $count-1);
		return RST($rows['rst'][$rand]);
	}
	
	/**
	 * 在静态变量中获取随机帐号
	 */
	function _getRandomAccountInMem(){
		static $_ramdom = array();
		static $_count = null;
		
		if(!empty($_ramdom)){
			return RST($_ramdom);
		}
		
		if(null === $_count){
			$_count = $this->getCount();
			$_count = $_count['rst'];
		}
		
		if($_count < 1){
			return RST(false);
		}
		
		$rand = rand(0, $_count-1);
		
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);
		$rs = $db->query('SELECT * FROM '. $db->getTable(T_ACCOUNT_PROXY) . " LIMIT {$rand}, 1");
		if(isset($rs[0])){
			$_ramdom = $rs[0];
			return RST($_ramdom);
		}else{
			$_count = 0;
			return RST(false);
		}
		
	}
	
	/**
	 * 获取总数
	 */
	function getCount(){
		$db = APP::ADP('db');
		$db->setTable(T_ACCOUNT_PROXY);
		$rs = $db->getOne('SELECT count(*) FROM '. $db->getTable(T_ACCOUNT_PROXY));
		return RST((int)$rs);
	}
	
}