<?php

require_once 'common.php';

$db = Db::getInstance();
$rows = $db->getRows($db->q("SELECT status, count(*) as cnt FROM beathaven.queue GROUP BY status"));
$info = array_fill(0, 3, 0);
foreach ($rows as $row) {
	$info[$row['status']] = $row['cnt'];
}

$tmp = array_slice(scandir(Config::get('app:Parser:bot_stats_dir')), 2);
$bots = array();
foreach($tmp as $bfile) {
	$bots[str_replace('.json', '', $bfile)] = json_decode(file_get_contents(Config::get('app:Parser:bot_stats_dir').$bfile));
}
foreach($bots as $name => $bot) {
	$tmp = exec("ps ".$bot->pid);
	$bot->active = (int) (strpos($tmp, strval($bot->pid)) !== false);
} 
?>
<html>
	<head>
		<title>BeatHaven</title>
		<meta http-equiv="refresh" content="5" />
		<style>
		body, td {padding:0;margin:0;font: 0.8em Georgia;}
		body {background-color:#112;}
		.status-3 {font: 10em Georgia; color: #FFF;}
		.status-02 {color: #AAA;}
		.running-1 {color: #8A8;}
		.running-0 {color: #A88;}
		.bots-stats {margin: 2em;}
		.bots-stats td {padding: 0.5em; color:#AAA;}
		.bots-stats tr.stats-head td {font-weight: bold;}
		</style>
	</head>
	<body>
		<table width="100%" height="100%">
			<tr>
				<td align="center" valign="middle">
					<div style="float:left;width:100px;height:1;">&nbsp;</div>
					<span class="status-3"><?= $info[6] ?></span>
					<span class="status-02"> / <?= $info[3] ?> / <?= $info[2] ?></span><br/>
					
					<table class="bots-stats">
						<tr class="stats-head">
							<td></td>
							<td>Started</td>
							<td>Finished</td>
							<td>PID</td>
							<td>Good</td>
							<td>Bad</td>
							<td>Queue</td>
							<td>Last</td>
						</tr>
						<? foreach($bots as $name => $bot): ?>
						<tr>
							<td><b class="running-<?= $bot->active ?>"><?= $name ?></b></td>
							<td><?= date('Y-m-d H:i:s', $bot->started_job) ?></td>
							<td><?= ($bot->active ? '&mdash;' : date('Y-m-d H:i:s', $bot->eneded_job)) ?></td>
							<td><?= $bot->pid ?></td>
							<td><?= $bot->good_results ?></td>
							<td><?= $bot->bad_results ?></td>
							<td><?= $bot->queue_size ?></td>
							<td><div style="width:20em;height:1.2em;overflow:hidden;"><nobr><?= $bot->last_request ?></nobr></div></td>
						</tr>
						<? endforeach; ?>
					</table>
				</td>
			</tr>
		</table>
	</body>
</html>