<?php
namespace KIF\Debug;
use KIF\Debug\FirePHP;
use KIF\Core\Config;

/**
 * 
 * Enter description here ...
 * @author gaoxiaogang
 * 用例:
 * KIF\Debug\Debug::start();// 打开
 * register_shutdown_function(array('KIF\Debug\Debug', 'show'));
 */
class Debug
{
	/**
	 * @desc Debug开关,默认为关闭
	 * @var bool
	 */
	static $open = false ;
	/**
	 * @desc Debug类实例化对象
	 * @var bool
	 */
	static $instance = false;
	/**
	 * @desc 运行时间显示数组
	 * @var array
	 */
	static $time_table = array();
	/**
	 * @desc 用户自定义中间变量显示数组
	 * @var array
	 */
	static $log_table = array();
	/**
	 * @desc 数据库查询执行时间数组
	 * @var array
	 */
	static $db_table = array();
	/**
	 * @desc 缓存查询执行时间数组
	 * @var array
	 */
	static $cache_table = array();

	/**
	 *
	 * 全文检索sphinx查询执行时间数组
	 * @var array
	 */
	static $sphinx_table = array();
	/**
	 * @desc 表单方式的接口
	 */
	static $form_table = array();
	/**
	 * @desc 起始时间
	 * @var int
	 */
	static $begin_time;
	/**
	 * @name __construct
	 * @desc 构造函数
	 */
	protected function __construct()
	{

	}
	/**
	 * @name start
	 * @desc 启动debug类
	 * @return null
	 */
	static public function start()
	{
		self::$open = true;
		self::$begin_time = microtime();
		self::$time_table = array(array('Description', 'Time', 'Caller'));
		self::$log_table = array(array('Label', 'Results', 'Caller'));
	}
	/**
	 * @name getTime
	 * @desc 获得从起始时间到目前为止所花费的时间
	 * @return int
	 */
	static public function getTime()
	{
		if(false === self::$open)
		{
			return ;
		}
    	list($pusec, $psec) = explode(" ", self::$begin_time);
    	list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec - (float)$pusec) + ((float)$sec - (float)$psec);
	}
	/**
	 * @name getInstance
	 * @desc 返回debug类的实例
	 * @return object
	 */
	static public function getInstance()
	{
		if(false === self::$instance)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	/**
	 * @name log
	 * @desc 记录用户自定义变量
	 * @param string $label 自定义变量显示名称
	 * @param mixed $results 自定义变量结果
	 * @param string $callfile 调用记录用户自定义变量的文件名
	 * @return null
	 * @access public
	 */
	static public function log($label, $results = '', $caller = '')
	{
		if(false === self::$open || (defined('DEBUG_SHOW_LOG') && !DEBUG_SHOW_LOG))
		{
			return ;
		}
		array_push(self::$log_table, array($label, $results, $caller));
	}
	/**
	 * @name db
	 * @desc 记录数据库查询操作执行时间
	 * @param string $ip 数据库IP
	 * @param int $port 数据库端口
	 * @param string $sql 执行的SQL语句
	 * @param float $times 花费时间
	 * @param mixed $results 查询结果
	 * @return null
	 * @access public
	 */
	static public function db($ip, $database ,$sql, $times, $results)
	{
		if(false === self::$open || (defined('DEBUG_SHOW_DB') && !DEBUG_SHOW_DB))
		{
			return ;
		}
		array_push(self::$db_table, array($ip, $database, $times, $sql, $results));
	}
	/**
	 * @name cache
	 * @desc 缓存查询执行时间
	 * @param array $server 缓存服务器及端口列表
	 * @param string $key 缓存所使用的key
	 * @param float $times 花费时间
	 * @param mixed $results 查询结果
	 * @return null
	 * @access public
	 */
	static public function cache($server, $key, $times, $results, $method = null)
	{
		if(false === self::$open || (defined('DEBUG_SHOW_CACHE') && !DEBUG_SHOW_CACHE))
		{
			return ;
		}
		array_push(self::$cache_table, array($server ,$key, $times, $results, $method));
	}

	/**
	 * @name 全文检索sphinx
	 * @desc 全文检索sphinx查询执行时间
	 * @param array $condition 查询条件
	 * @param float $times 花费时间
	 * @param mixed $results 查询结果
	 * @return null
	 * @access public
	 */
	static public function sphinx($condition, $times, $results, $method = null)
	{
		if(false === self::$open || (defined('DEBUG_SHOW_SPHINX') && !DEBUG_SHOW_SPHINX))
		{
			return ;
		}
		array_push(self::$sphinx_table, array($condition, $times, $results, $method));
	}

	/**
	 * @name time
	 * @desc 记录程序执行时间
	 * @param string $desc 描述
	 * @param mixed $results 结果
	 * @return null
	 * @access public
	 */
	static public function time($desc, $caller)
	{
		if(false === self::$open || (defined('DEBUG_SHOW_TIME') && !DEBUG_SHOW_TIME))
		{
			return ;
		}
		array_push(self::$time_table, array($desc, self::getTime(), $caller));
	}
	/**
	 * 记录form表单的方式接口请求
	 * @param label 说明标签
	 * @param action 表单的请求地址
	 * @param params 表单的数据项
	 * @param caller 处理程序
	 */
	static public function form($label, $action, $params = array(),$method='post', $times = 0, $results = '', $caller = __FILE__)
	{
		if (false === self::$open || (defined('DEBUG_SHOW_FORM') && !DEBUG_SHOW_FORM))
		{
			return ;
		}
		$form_html = '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8" /><title>Debug Form</title></head><body><form action="'.$action.'" method="'.$method.'">';
		if ($params)
		{
			foreach ($params as $k => $v)
			{
				$form_html .= $k.': <input type="text" name="'.$k.'" value="'.$v.'" /><br/>';
			}
		}
		$form_html .= '<input type="submit" value="submit" /></form></body></html>';
		array_push(self::$form_table, array($label, $form_html, $times, $results, $caller));
	}
	/**
	 * @name fb
	 * @desc 调用FirePHP函数
	 * @return mixed
	 * @access public
	 */
	static public function fb()
	{
		$instance = FirePHP::getInstance(true);
		$args = func_get_args();
		return call_user_func_array(array($instance,'fb'),$args);
	}
	/**
	 * @name show
	 * @desc 显示调试信息
	 * @todo 目前只实现了在FirePHP中显示结果.需要实现记录LOG日志形式
	 * @return null
	 * @access public
	 */
	static public function show()
	{
		if (!defined('DEBUG_SHOW_LOG') || (defined('DEBUG_SHOW_LOG') && DEBUG_SHOW_LOG))
		{
			//用户记录变量
			self::fb(array('Custom Log Object', self::$log_table), FirePHP::TABLE );
		}
		if (!defined('DEBUG_SHOW_TIME') || (defined('DEBUG_SHOW_TIME') && DEBUG_SHOW_TIME))
		{
			//页面执行时间
			self::fb(array('This Page Spend Times ' . self::getTime(), self::$time_table), FirePHP::TABLE );
		}

		/*---------记录至日记文件中------------*/
		/*
		if(count(self::$log_table) > 1 || count(self::$time_table) > 1)
		{
			if(isset($_SERVER['TERM']))
			{
				$string = "PWD:" . $_SERVER['PWD'] . "\n";
				$string .= "SCRIPT_NAME:" . $_SERVER['SCRIPT_NAME'] . "\n";
				$string .= "ARGV:" . var_export($_SERVER['argv'], true) . "\n";
			}else
			{
				$string = "HTTP_HOST:" . $_SERVER['HTTP_HOST'] . "\n";
				$string .= "SCRIPT_NAME:" . $_SERVER['SCRIPT_NAME'] . "\n";
				$string .= "QUERY_STRING:" . $_SERVER['QUERY_STRING'] . "\n";
			}
			$string .= 'This Page Spend Times:' . self::getTime() . "\n";
			array_shift(self::$log_table);
			array_shift(self::$time_table);
			if(!empty(self::$time_table))
			{
				$string .= "\n";
				foreach (self::$time_table as $v)
				{
					$string .= "|--  ".$v[0]."  ".$v[1]."  ".$v[2]."  --|\n";
				}
			}
			if(!empty(self::$log_table))
			{
				$string .= "\n";
				foreach (self::$log_table as $v)
				{
					$string .= "|----  ".$v[0]."  ".$v[2]."  ----|\n";
					$string .= var_export($v[1], true) . "\n";
				}
			}
			$filename = "debug_" . date("Ymd") . ".log";
			Log::customLog($filename, $string);
		}
		*/
		//数据库执行时间
		if(count(self::$db_table) > 0)
		{
			$i = 0 ;
			$db_total_times = 0 ;
			foreach (self::$db_table as $v)
			{
				$db_total_times += $v[2];
				$i++;
			}
			array_unshift(self::$db_table, array('IP', 'Database', 'Time', 'SQL Statement','Results'));
			self::fb(array($i . ' SQL queries took '.$db_total_times.' seconds', self::$db_table), FirePHP::TABLE );
		}
		//Cache执行时间
		if(count(self::$cache_table) > 0)
		{
			$i = 0 ;
			$cache_total_times = 0 ;
			foreach (self::$cache_table as $v)
			{
				$cache_total_times += $v[2];
				$i++;
			}
			array_unshift(self::$cache_table, array('Server', 'Cache Key', 'Time','Results', 'Method'));
			self::fb(array($i.' Cache queries took '.$cache_total_times.' seconds', self::$cache_table), FirePHP::TABLE );
		}
		//sphinx执行时间
		if(count(self::$sphinx_table) > 0)
		{
			$i = 0 ;
			$sphinx_total_times = 0 ;
			foreach (self::$sphinx_table as $v)
			{
				$sphinx_total_times += $v[1];
				$i++;
			}
			array_unshift(self::$sphinx_table, array('Condition', 'Time','Results', 'Method'));
			self::fb(array($i.' Sphinx queries took '.$sphinx_total_times.' seconds', self::$sphinx_table), FirePHP::TABLE );
		}
		//Form执行时间
		if(self::$form_table)
		{
			$i = 0;
			$form_total_times = 0;
			foreach (self::$form_table as $v)
			{
				$form_total_times += $v[2];
				$i++;
			}
			array_unshift(self::$form_table, array('Label', 'FormHtml', 'Times', 'Results', 'Caller'));
			self::fb(array($i.' Form action request took '.$form_total_times.' seconds', self::$form_table), FirePHP::TABLE );
		}

		if (!defined('DEBUG_SHOW_UTILITY') || (defined('DEBUG_SHOW_UTILITY') && DEBUG_SHOW_UTILITY))
		{
			//自定义函数
			$functions = get_defined_functions();
			//定义的常量
			$constants = get_defined_constants(true);
			$sessions = isset($_SESSION) ? $_SESSION : array();
			self::fb(array('Utility Variables',
					  array(
						array('name', 'values'),
						array('GET Variables', $_GET),
						array('POST Variables', $_POST),
						array('Custom Defined Functions', $functions['user']),
						array('Include Files', get_included_files()),
						array('Defined Constants', $constants['user']),
						array('SESSION Variables', $sessions),
						array('SERVER Variables', $_SERVER),
						array('appConfigs', Config::all())
					  )
			), FirePHP::TABLE );
		}
	}
}