{% load i18n %}
{% load url from future %}
{% load static %}

<html><head> 
    <title>{% trans "Service Status Dashboard" %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Remy van Elst">
    <meta name="author" content="Pall Sigurdsson">
    <meta http-equiv="refresh" content="30">
    <meta http-equiv="X-UA-Compatible" content="IE=9">
    <link href="{% url "media" path="external/bootstrap/css/bootstrap-3.1.1.min.css" %}" rel="stylesheet">
    <script type="text/javascript"src="{% url "django.views.i18n.javascript_catalog" %}"></script>
    <style type="text/css">
        a {
            color: #333 !important;
        }
        .alert { 
            padding:5px 13px !important;
            border-radius: 0px !important;
            margin-bottom: 2px !important;
        }

    </style>
</head>

<body>
    <div class="row">
        <div class="col-md-12">
            <h1 class="pull-left">{% trans "Status Dashboard" %}</h1>
            <div id="top-right" class="pull-right">
                <div> {% blocktrans with user=request.META.REMOTE_USER addr=request.META.REMOTE_ADDR %}You are {{ user }} coming from {{ addr }}.{% endblocktrans %} </div>
                <div id="information_dialog" class="dynamic"></div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <span id="total_hosts" class="dynamic">...</span> {% trans "Hosts." %}
            <span id="total_services" class="dynamic">...</span> {% trans "Services." %}
            <div id="summary" class="alert">
                <h2>
                    <span id="unhandled_services" class="dynamic">...</span> {% trans "Unhandled Service problems." %}
                    <span id="unhandled_hosts" class="dynamic">...</span> {% trans "Unhandled Host Problems!" %}
                </h2>
            </div>
        </div>
    </div>

<div class="row">
    <div class="col-md-6">

        <h3>{% trans "Hosts Down" %}</h3>
        <div id="hosts_down_unhandled" class="dynamic"></div>


        <h3>{% trans "Critical Issues" %}</h3>
        <div id="services_major_unhandled"  class="dynamic"></div>


        <h3>{% trans "Hosts Acknowledged Down" %}</h3>
        <div id="hosts_down_handled"  class="dynamic"></div>



    </div>

    <div class="col-md-6">

        <h3>{% trans "Minor Issues" %} </h3>
        <div id="services_minor_unhandled"  class="dynamic"></div>

        <h3>{% trans "Acknowledged Criticals" %}</h3>
        <div id="services_major_handled"  class="dynamic"></div>

        <h3>{% trans "Acknowledged Minor Issues" %}</h3>
        <div id="services_minor_handled"  class="dynamic"></div>

    </div>
</div>

<br>

<div class="row">
    <div class="container text-center">
    <span>{% blocktrans %}Based on a dashboard by <a href="https://raymii.org">Remy van Elst (code)</a> and <a href="https://github.com/JobV">Job van der Voort (design)</a>." %}{% endblocktrans %}</span>
    </div>
</div>



<!-- This is a container for how to display a typical service problem -->
<div class="hide" id="service_prototype">
    <div class="alert CSSHINT">
        {% url "adagios.status.views.detail" as the_url %}
	{% blocktrans %}
        <a href="{{ the_url }}?host_name=HOST&service_description=SERVICE"> #NUMBER <b>SERVICE</b> on <i>HOST</i></a> OUTPUT
	{% endblocktrans %}
    </div>
</div>

<!-- The javascript below uses this div to populate an "ok" part of the dashboard -->
<div class="hide" id="everything_is_ok_template">
    <div class="alert alert-success">
        <span class="glyphicon glyphicon-thumbs-up"> </span> &nbsp; <span class="glyphicon glyphicon-thumbs-up"> </span> &nbsp; {% trans "Everything is looking good!" %}
    </div>
</div>


<!-- This is a container for how to display a typical host problem -->
<div class="hide" id="host_prototype">
    <div class="alert CSSHINT">
        {% url "adagios.status.views.detail" as the_url %}
        {% blocktrans %}
	<a href="{{ the_url }}?host_name=HOST"> #NUMBER <b>HOST</b> </a> OUTPUT
	{% endblocktrans %}
    </div>
</div>

<div class="hide" id="loading_dialog">
    {% trans "Loading..." %}
</div>



<!-- Placed at the end of the document so the pages load faster -->
<script src="{% url "home" %}rest/pynag.js"></script>
<script src="{% url "home" %}rest/status.js"></script>
<script src="{% url "home" %}rest/okconfig.js"></script>
<script src="{% url "home" %}rest/adagios.js"></script>

<script src="{% url "media" path="external/jquery/jquery-1.9.1.min.js" %}"></script>
<script src="{% url "media" path="external/bootstrap/js/bootstrap.min.js" %}"></script>

<script src="{% url "media" path="external/datatables/js/jquery.dataTables.min.js" %}"></script>
<script src="{% url "media" path="external/datatables/DT_bootstrap.js" %}"></script>

<script src="{% url "media" path="external/select2/select2.min.js" %}" type="text/javascript"></script>
<script src="{% url "media" path="js/adagios.js" %}"></script>
<script src="{% url "media" path="js/adagios_status.js" %}"></script>

<script src="{% url "media" path="external/datepicker/js/bootstrap-datepicker.js" %}"></script>


<script type="text/javascript" xmlns="http://www.w3.org/1999/html">
    var last_load;

    $(document).ready(function() {
            initilize_dashboard();
            setInterval(update_last_loaded, 1000);
    });

    // Collect all service and host problems, gather needed statistics
    // To populate problem boxes
    function initilize_dashboard() {
        var loading_dialog = $("#loading_dialog").html();
        $('.dynamic').html(loading_dialog);
        update_statistics();
        update_all_services();
        update_all_hosts();
    }

    // Update the dialog which says how many seconds ago last load was.
    function update_last_loaded() {
        $("#information_dialog").text(interpolate(gettext("Last update %s ago."), [timeSince(last_load)]));
    }

    function error_message(message) {
        $("body").html(interpolate(gettext("<h1>Oh no, there was an error loading the page :/</h1> %s"), [message.responseText]));
        console.error(message);
    }

    // Updates dialogs like total number of hosts and services
    function update_statistics() {
        var parameters = get_querystring_dict();
        var statistics = adagios.rest.status.statistics(parameters)
                .fail(function(data) {
                        error_message(data);
                })
                .done(function(data) {
                    var total_services = data['total_services'];
                    var total_hosts = data['total_hosts'];
                    $("#total_hosts").text(total_hosts);
                    $("#total_services").text(total_services);
                    $('#unhandled_hosts').text(data['unhandled_hosts']);
                    $('#unhandled_services').text(data['unhandled_services']);

                    if (data['unhandled_hosts'] === 0 && data['unhandled_services'] === 0) {
                        $("#summary").addClass('alert-success');
                    }
                    else {
                        $("#summary").addClass('alert-danger');
                    }

                });
    }
    // Downloads all service problems and updates relevant parts on the dashboard.
    function update_all_hosts() {
        var parameters = get_querystring_dict();
        parameters['fields'] = "name state plugin_output scheduled_downtime_depth acknowledged";
        parameters['state__isnot'] = "0";
        var all_hosts = adagios.rest.status.hosts(parameters)
                .fail(function(data) {
                        error_message(data);
                })
                .done(function(data) {
                    var hosts_down_handled = [];
                    var hosts_down_unhandled = [];
                    var current_host;
                    for (var i=0;i < data.length; i = i + 1) {
                        current_host = data[i];
                        if (current_host['state'] == 0) {
                            continue;
                        }
                        if (current_host['acknowledged'] == 0 && current_host['scheduled_downtime_depth'] == 0) {
                            hosts_down_unhandled.push(current_host);
                        }
                        else {
                            hosts_down_handled.push(current_host);
                        }
                    }
                    fill_a_div_with_hosts("hosts_down_handled", hosts_down_handled, 'alert-info' );
                    fill_a_div_with_hosts("hosts_down_unhandled", hosts_down_unhandled, 'alert-danger' );

                });
    }

    // Downloads all service problems and updates relevant parts on the dashboard.
    function update_all_services() {
        var parameters = get_querystring_dict();
        parameters['fields'] = "host_name state description plugin_output scheduled_downtime_depth acknowledged";
        parameters['state__isnot'] = "0";
        parameters['host_state'] = "0";
        var services_all = adagios.rest.status.services(parameters)
            .fail(function(data) {
                    error_message(data);
                })
            .done(function(services_all) {
                    var services_minor_handled = [];
                    var services_minor_unhandled = [];
                    var services_major_handled = [];
                    var services_major_unhandled = [];
                    var tmp;
                    var state, ack, downtime;
                    for (var i=0;i < services_all.length; i = i + 1) {
                        tmp = services_all[i];
                        state = tmp['state'];
                        ack = tmp['acknowledged'];
                        downtime = tmp['scheduled_downtime_depth'];

                        // Skip ok services
                        if (state === 0) {
                            // Do nothing.
                        }
                        else if (ack === 0 && downtime === 0 && state === 1) {
                            services_minor_unhandled.push(tmp);
                        }
                        else if (ack === 0 && downtime === 0 && state > 1) {
                            services_major_unhandled.push(tmp);
                        }
                        else if (state === 1) {
                            services_minor_handled.push(tmp);
                        }
                        else if (state > 1) {
                            services_major_handled.push(tmp);
                        }
                        else {
                            error_message(gettext("There is a problem with classifying the following service problem:"));
                            error_message(tmp);
                        }


                    }



                    fill_a_div_with_services("services_major_handled", services_major_handled, 'alert-info');
                    fill_a_div_with_services("services_major_unhandled", services_major_unhandled, 'alert-danger');

                    fill_a_div_with_services("services_minor_handled", services_minor_handled, 'alert-info');
                    fill_a_div_with_services("services_minor_unhandled", services_minor_unhandled, 'alert-warning');

                    last_load = new Date();
        });
    }

    // Fills #div_id with a service_list, with bootstrap "alert" lists.
    function fill_a_div_with_services(div_id, service_list, alert_type) {
        // This div is our template div, all style is configured in there.
        var destination_div = $("#" + div_id);
        var prototype_html = $("#service_prototype").html();
        var html = '';
        var i;

        if (destination_div.length == 0) {
            console.error("no element found with id=" + div_id );
            return destination_div;
        }

        for (var k=0; k< service_list.length; k += 1) {
            i = service_list[k];
            // html is the variable where our markup is stored.
            html += prototype_html
                    .replace(/HOST/g, i['host_name'])
                    .replace(/SERVICE/g, i['description'])
                    .replace(/CSSHINT/g, alert_type)
                    .replace(/OUTPUT/g, i['plugin_output'])
                    .replace(/NUMBER/g, k+1);
        }

        // If there are no services, lets display a nice green box
        if (html == '') {
            html = $("#everything_is_ok_template").html();
        }

        // Here we update the html of our destination div
        destination_div.html(html);
        return destination_div;

    }

    // Fills div_id with nice looking markup for host problems. If host_list is empty,
    // Put a nice green dialog in there saying everything is ok.
    function fill_a_div_with_hosts(div_id, host_list, alert_type) {
        var destination_div = $("#" + div_id);
        var prototype_html = $("#host_prototype").html();
        var html = '';
        var i;

        if (destination_div.length == 0) {
            console.error("no element found with id=" + div_id );
            return destination_div;
        }

        for (var k=0; k< host_list.length; k += 1) {
            i = host_list[k];
            // html is the variable where our markup is stored.
            html += prototype_html
                    .replace(/HOST/g, i['name'])
                    .replace(/CSSHINT/g, alert_type)
                    .replace(/OUTPUT/g, i['plugin_output'])
                    .replace(/NUMBER/g, k+1);
        }

        // If there are no hosts, lets display a nice green box
        if (html == '') {
            html = $("#everything_is_ok_template").html();
        }

        // Here we update the html of our destination div
        destination_div.html(html);
        return destination_div;
    }

    // Return a human friendly version of how long since a specific date.
    function timeSince(date) {
        var seconds = Math.floor((new Date() - date) / 1000);

        var interval = Math.floor(seconds / 31536000);

        if (interval > 1) {
            return interval + gettext(" years");
        }
        interval = Math.floor(seconds / 2592000);
        if (interval > 1) {
            return interval + gettext(" months");
        }
        interval = Math.floor(seconds / 86400);
        if (interval > 1) {
            return interval + gettext(" days");
        }
        interval = Math.floor(seconds / 3600);
        if (interval > 1) {
            return interval + gettext(" hours");
        }
        interval = Math.floor(seconds / 60);
        if (interval > 1) {
            return interval + gettext(" minutes");
        }
        return Math.floor(seconds) + gettext(" seconds");
    }
    // Return current querystring parameters as key-value pairs
    function get_querystring_dict() {
        var result = {};
        var tmp = location.search.substr(1).split("&");
        var i, item, key, value;
        for (i = 0; i<tmp.length; i += 1) {
            item = tmp[i];
            key = item.split("=")[0];
            value =  item.split("=")[1];
            result[key] = value;
        }
        return result;
    }


</script>
</body>
</html>
