<?php
require_once(dirname(__FILE__) . '/../dashlet-helper.inc.php');

dashlets_data_check();

top_alerts_dashlet();

function top_alerts_get_unique_host_service_name($server, $host, $service) {

	return $server . '+++++' . $host . '+++++' . $service;
}

function top_alerts_dashlet() {

    $server_id = grab_request_var('server', 'all');
	$top_alerts = array();

	// last 24 hours
	$current_time = time();
	$cutoff_time = $current_time - (24 * 60 * 60);

	$servers = get_servers();
	foreach ($servers as $server) {

		if ($server_id != 'all') {
			if ($server['server_id'] != $server_id) {
				continue;
			}
		}

		$alert_list = get_server_polled_key($server, 'alert_list');
		$alert_list = array_map('alert_list_to_human_readable', $alert_list);

		if (count($alert_list) > 0) {
			foreach ($alert_list as $index => $alerts) {
				if (isset($alerts['alert_list'])) {
					foreach ($alerts['alert_list'] as $alert) {

						if (isset($alert['time']) && ($time = strtotime($alert['time'])) >= $cutoff_time) {
							
							$uid = top_alerts_get_unique_host_service_name($server['server_id'], $alert['host'], $alert['service']);

							if (!isset($top_alerts[$uid]))
								$top_alerts[$uid] = array(
									'host' => $alert['host'],
									'service' => $alert['service'],
									'count' => 1,
									'server_name' => $server['name'],
									'server_id' => $server['server_id'],
									);
							else
								$top_alerts[$uid]['count'] = $top_alerts[$uid]['count'] + 1;
						}
					}
				}
			}
		}
	}

	// order them by count
	usort($top_alerts, 'sort_alerts_by_count');


	// we only care about the top 15, and lets rank them
	$count = 0;
	foreach ($top_alerts as $index => $top_alert) {

		$top_alerts[$index]['rank'] = ++$count;
		if ($count >= 15)
			break;
	}


	echo '
		<style>
		table.alerts th { cursor: pointer; }
		</style>
		<script type="text/javascript">
	    $(function() {
	        $("table.alerts").tablesorter({ });
	    });
		</script>
		<table class="alerts tactical table table-no-margin table-condensed table-striped table-bordered host_status_summary_dashlet borderless service_status_summary_dashlet borderless infotable">
			<thead>
				<tr>
					<th>' . _('Server') . '</th>
					<th>' . _('Host') . '</th>
					<th>' . _('Service') . '</th>
					<th>' . _('Rank') . '</th>
					<th>' . _('Alert Count') . '</th>
				</tr>
			</thead>
			<tbody>';

	if (count($top_alerts) > 0) {
		foreach ($top_alerts as $alert) {
			top_alerts_dashlet_build_row($alert);
		}
	} else {
        echo '<tr><td colspan="5" style="text-align: center;">' . _('You have no top alerts!') . '</td></tr>';
	}

	echo '</tbody></table>';
}

function top_alerts_dashlet_build_row($alert) {

	// we need all this
	if (   !isset($alert['server_name']) 
        || !isset($alert['server_id'])
		|| !isset($alert['host']) 
		|| !isset($alert['count']) 
		|| !isset($alert['rank']))
		return;

	if (empty($alert['service']))
		$alert['service'] = '';

    $server_link = get_server_base_url($alert['server_id'], $core_include_cgi = false);
    $server_link = '<a href="' . $server_link . '" target="_blank">' . encode_html($alert['server_name']) . '</a>';

    $host_link = get_tactical_link($alert['host'], $alert['server_id'], 
    "includes/components/xicore/status.php?show=hostdetail&host=" . urlencode($alert['host']),
    "extinfo.cgi?type=1&host=" . urlencode($alert['host']));

    $service_link = '';
    if (!empty($alert['service']))
        $service_link = get_tactical_link($alert['service'], $alert['server_id'],
            "includes/components/xicore/status.php?show=servicedetail&dest=auto&host=" . urlencode($alert['host']) . "&service=" . urlencode($alert['service']),
            "extinfo.cgi?type=2&host=" . urlencode($alert['host']) . "&service=" . urlencode($alert['service']));
    
	echo '
		<tr>
			<td>' . $server_link . '</td>
			<td>' . $host_link . '</td>
			<td>' . $service_link . '</td>
			<td>' . encode_html($alert['rank']) . '</td>
			<td>' . encode_html($alert['count']) . '</td>
		</tr>';
}


function sort_alerts_by_count($a, $b) {

	if (!empty($a['count']) && !empty($b['count']))
		return $a['count'] < $b['count'];

	return false;
}
