<?php

function fusioncore_poll_alerts(&$raw_data, $server = '') {
    $server = get_server($server);
    if ($server === false)
        return array();

    $alert_data = array();

    $xi = false;
    $core = false;

    // xi
    if (!empty($raw_data['logentries']['logentry'])) {
        $xi = true;
        $alerts = $raw_data['logentries']['logentry'];

        if ($raw_data['logentries']['recordcount'] == 1)
            $alerts = array($alerts);
    }

    // core
    if (!empty($raw_data['data']['alertlist'])) {
        $core = true;
        $alerts = $raw_data['data']['alertlist'];
    }

    // have to let the poller know we're not the one..
    if (!$xi && !$core)
        return null;
    
    foreach ($alerts as $alert) {
        $logentry = str_replace( array("\r", "\n", "&apos;"), array(" ", " ", "'"), $alert['logentry_data']);

        $time = null;
        $type = null;
        $host = null;
        $service = null;
        $state_type = null;
        $state = null;
        $output = null;

        // xi comes back from mysql datetime in the server's timezone
        // core is already epoch
        if (isset($alert['entry_time']))
            $time = convert_server_timestring_to_local_timestring($server, $alert['entry_time']);
        if (isset($alert['timestamp']))
            $time = date('Y-m-d H:i:s', substr($alert['timestamp'], 0, -3)); // core is in microseconds

        if (isset($alert['logentry_type']))
            $type = $alert['logentry_type'];

        // xi looks like: "SERVICE ALERT: HP48SW-01.nagios.local;Port 11 Status;CRITICAL;SOFT;1;CRITICAL: Interface 11 (index 11) is down."
        // so we break on the first :, and then explode on ; to get the parts of data we need
        if (isset($alert['logentry_data'])) {

            if (($colon_pos = strpos($logentry, ':')) !== false) {

                $logentry = substr($logentry, $colon_pos + 1);
                $logentry = explode(';', $logentry);

                $element = 0;

                if (!empty($logentry[$element]))
                    $host = trim($logentry[$element++]);

                // if this is a service?
                if (count($logentry) == 6 && !empty($logentry[$element]))
                    $service = trim($logentry[$element++]);

                if (!empty($logentry[$element]))
                    $state = trim($logentry[$element++]);

                if (!empty($logentry[$element]))
                    $state_type = trim($logentry[$element++]);

                // the next one is the count. we do nothing with that
                $element++;

                if (!empty($logentry[$element]))
                    $output = trim($logentry[$element]);
            }
        }

        if (isset($alert['host_name']))
            $host = $alert['host_name'];
        if (isset($alert['name']))
            $host = $alert['name'];

        if (isset($alert['description']))
            $service = $alert['description'];

        if (isset($alert['state']))
            $state = $alert['state'];

        if (isset($alert['state_type']))
            $state_type = $alert['state_type'];

        if (isset($alert['plugin_output']))
            $output = $alert['plugin_output'];

        // we need a type to store from core data
        if ($core) {

            if ($state_type == AU_STATETYPE_HARD)
                $state_type = 'HARD';
            else if ($state_type == AU_STATETYPE_SOFT)
                $state_type = 'SOFT';

            switch($state) {
                case AU_STATE_HOST_UP:
                    $type = NSLOG_HOST_UP;
                    $state = 'UP';
                    break;

                case AU_STATE_HOST_DOWN:
                    $type = NSLOG_HOST_DOWN;
                    $state = 'DOWN';
                    break;
                
                case AU_STATE_HOST_UNREACHABLE:
                    $type = NSLOG_HOST_UNREACHABLE;
                    $state = 'UNREACHABLE';
                    break;
                
                case AU_STATE_SERVICE_OK:
                    $type = NSLOG_SERVICE_OK;
                    $state = 'OK';
                    break;
                
                case AU_STATE_SERVICE_WARNING:
                    $type = NSLOG_SERVICE_WARNING;
                    $state = 'WARNING';
                    break;
                
                case AU_STATE_SERVICE_CRITICAL:
                    $type = NSLOG_SERVICE_CRITICAL;
                    $state = 'CRITCAL';
                    break;
                
                case AU_STATE_SERVICE_UNKNOWN:
                    $type = NSLOG_SERVICE_UNKNOWN;
                    $state = 'UNKNOWN';
                    break;
            }
        }
  
        if (!empty($host) && !empty($time)) 
            $alert_data[] = array(
                'time' => $time,
                'type' => $type,
                'host' => $host,
                'service' => $service,
                'state_type' => $state_type,
                'state' => $state,
                'output' => $output,
                );
    }

    return array('alert_list' => $alert_data);
}

function nls_alerts(&$raw_data) {

    $alerts = array();

    if (!isset($raw_data['hits']['hits']))
        return $data;

    $hits = $raw_data['hits']['hits'];

    if (!is_array($hits))
        return $data;

    foreach ($hits as $i => $hit) {

        if (!isset($hit['_source']))
            continue;

        $source = $hit['_source'];

        if (   !isset($source['name'])
            || !isset($source['check_interval'])
            || !isset($source['lookback_period'])
            || !isset($source['warning'])
            || !isset($source['critical'])
            || !isset($source['created_by']))
            continue;

        $alerts[] = array(
            'id'=>$hit['_id'],
            'name'=>$source['name'],
            'check_interval'=>$source['check_interval'],
            'lookback_period'=>$source['lookback_period'],
            'warning'=>$source['warning'],
            'critical'=>$source['critical'],
            'created_by'=>$source['created_by'],
            'created'=>$source['created'],
            'alert_crit_only'=>$source['alert_crit_only'],
            'warning_threshold' => $source['warning'],
            'critical_threshold' => $source['critical'],
            'last_run' => $source['last_run'],
            'next_run' => $source['next_run'],
            'active' => $source['active'],
            'alert_method' => $source['method'],
            'last_status' => $source['last_status'],
            'last_output' => $source['last_output'],
            'query' => $source['query'],
            'dash_query' => $source['dash_query'],
            );
    }

    return array('alerts' => $alerts);
}

function nls_alert_history(&$raw_data) {

    $alert_history = array();

    if (!isset($raw_data['hits']['hits']))
        return $data;

    $hits = $raw_data['hits']['hits'];

    if (!is_array($hits))
        return $data;

    foreach ($hits as $i => $hit) {

        if (!isset($hit['_source']))
            continue;
    
        $source = $hit['_source'];

        if (   !isset($source['name'])
            || !isset($source['check_interval'])
            || !isset($source['lookback_period'])
            || !isset($source['warning'])
            || !isset($source['critical']))
            continue;

        $alert_history[] = array(
            'alert_name' => $source['name'],
            'id' => $hit['_id'],
            'check_interval' => $source['check_interval'],
            'lookback_period' => $source['lookback_period'],
            'warning_threshold' => $source['warning'],
            'critical_threshold' => $source['critical'],
            'ran' => $source['ran'],
            'status' => $source['status'],
            'output' => $source['output'],
            'query' => $source['query'],
            );
    }
    
    return array('alert_history' => $alert_history);
}

function nna_alerts(&$raw_data) {

	$alerts = array();
    
    foreach ($raw_data as $i => $alert) {
        $alerts[] = array(
            'name' => $alert['name'],
            'lastrun' => $alert['lastrun'],
            'lastcode' => $alert['lastcode'],
            'laststdout' => $alert['laststdout'],
        );
    }

	return array('nna_alerts' => $alerts);

}
