<?php

class DebugExecutionTime {

	private $_log = array();
	private $_logByGroups = array();
	private $_isActive = false;
	private $_lastTime = 0;

	public function __construct() {
		$this->_log = array();
	}

	public function activate() {
		$this->_isActive = true;
	}

	public function log($msg, $groups = array()) {
		if (!$this->_isActive) return;
		$curTime = microtime(true);
		$execTime = (!$this->_lastTime)? 0 : $curTime - $this->_lastTime;
		$this->_lastTime = $curTime;

		$this->_log[] = array($msg, $execTime);

		foreach ($groups as $group) {
			if (!array_key_exists($group, $this->_logByGroups)) $this->_logByGroups[$group] = 0;
			$this->_logByGroups[$group] += $execTime;
		}
	}

	public function printDebug() {
		if (!$this->_isActive) return;
		$sumExecTime = 0;
		foreach ($this->_log as $log) $sumExecTime += $log[1];
		?>
		<table>
			<tr>
				<td style="vertical-align:top;">
					<div style="max-height:300px;overflow:auto">
		<table style="text-align:left;" border="1" cellspacing="0" cellpadding="1">
			<thead>
				<tr>
					<th>msg</th>
					<th>time</th>
				</tr>
			</thead>
			<tfoot>
				<th style="text-align:right">total:</th>
				<th style="font-family:monospace;text-align:right;font-weight:bold;"><?php echo number_format($sumExecTime, 6); ?></th>
			</tfoot>
			<tbody>
				<?php foreach ($this->_log as $log) : ?>
					<tr>
						<td><?php echo $log[0]; ?></td>
						<td style="font-family:monospace;text-align:right;"><?php echo number_format($log[1], 6); ?></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
					</div>
				</td>
				<td style="vertical-align:top;">

		<?php if (!empty($this->_logByGroups)) : ?>
		<table style="text-align:left;" border="1" cellspacing="0" cellpadding="1">
			<thead>
				<tr>
					<th>group</th>
					<th>time</th>
					<th>time left</th>
					<th>time %</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($this->_logByGroups as $group => $execTime) : ?>
					<tr>
						<th><?php echo $group; ?></th>
						<td style="font-family:monospace;text-align:right;"><?php echo number_format($execTime, 6); ?></td>
						<td style="font-family:monospace;text-align:right;"><?php echo number_format($sumExecTime - $execTime, 6); ?></td>
						<td style="font-family:monospace;text-align:right;"><?php echo (!$execTime)? 0 : round($execTime * 100 / $sumExecTime); ?>%</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php endif; ?>

				</td>
			</tr>
		</table>
		<?php
	}

}
