<!doctype html>
<html lang="en">
    <head>
        <title>{{ hostname.capitalize() }} live monitoring</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="{{ url_for('v1.static', filename='design.css') }}"/>
        <link rel="stylesheet" href="{{ url_for('v1.static', filename='select2/select2.css') }}"/>
        <link rel="icon" type="image/png" href="{{ url_for('v1.static', filename='favicon.png') }}" />
        <script src="{{ url_for('v1.static', filename='jquery-1.9.1.min.js') }}"></script>
        <script src="{{ url_for('v1.static', filename='jquery.cookie-1.4.0.min.js') }}"></script>
        <script src="{{ url_for('v1.static', filename='jquery.numeric-1.3.1.min.js') }}"></script>
        <script src="{{ url_for('v1.static', filename='select2/select2.min.js') }}"></script>
        <script>
            var multiprobes = false;
            function startRefreshing() {
                stopRefreshing();
                timer = setInterval('reloadAllImages("last")', {{ refresh*1000 }});
            }

            function startRefreshingFixedStart() {
                stopRefreshing();
                timer = setInterval('reloadAllImages("fixedStart")', {{ refresh*1000 }});
            }

            function stopRefreshing() {
                if(typeof timer != 'undefined') {
                    clearInterval(timer);
                }
            }

            function modifyPeriod(start, end) {
                $('.graph').each(function() {
                    var src = $(this).attr('src');
                    var probes = '';
                    if(src.indexOf('?') != -1) {
                        probes = src.substring(src.indexOf('?'));
                        src = src.substring(0, src.indexOf('?'));
                    }
                    var src_list = src.split('/');
                    src_list.pop();
                    src_list.pop();
                    src_list.pop();
                    $(this).attr('src', src_list.join('/') + '/' + start + '/' + end + '/' + probes);
                });
            }

            function reloadImage(img, mode) {
                var src = img.attr('src');
                var probes = '';
                if(src.indexOf('?') != -1) {
                    probes = src.substring(src.indexOf('?'));
                    src = src.substring(0, src.indexOf('?'));
                }
                var src_list = src.split('/');
                src_list.pop();
                var end = src_list.pop();
                var start = src_list.pop();
                var interval = end - start;
                var newEnd = Math.ceil(Date.now() / 1000);
                if(mode == 'last') {
                    var newStart = newEnd - interval;
                } else if(mode == 'fixedStart') {
                    var newStart = start;
                }
                img.attr('src', src_list.join('/') + '/' + newStart + '/' + newEnd + '/' + probes);
            }

            function reloadAllImages(mode) {
                $('.graph').each(function() {
                    reloadImage($(this), mode);
                });
            }

            function selectJobId() {
                deselectAll();
                job = $('#job-field').val();
                if(!job) {
                    return;
                }
                $('#loading-div-background').show();
                $.ajax({
                    url: '{{ url_for("v1.welcome") }}nodes/' + job + '/',
                    dataType: 'json',
                    success: function(data) {
                        stopRefreshing();
                        if(data.started_at == 'Undefined' ||
                           data.started_at >= Math.ceil(Date.now() / 1000)) {
                            alert('Job has not started');
                            $('#loading-div-background').hide();
                            startRefreshing();
                            return;
                        }
                        var items = data.nodes;
                        if(items.length === 0) {
                            alert('No hosts found');
                        }
                        var selected = [];
                        $.each(items, function(i, e) {
                            e = e.split('.');
                            e = e[1] + '.' + e[0];
                            probe = probeInSelect(e);
                            if($.inArray(probe, selected) != -1) {
                                return;
                            }
                            if(probe) {
                                selected[selected.length] = probe;
                                $('select').trigger({
                                    type: 'select2-selecting',
                                    val: probe
                                });
                                $('select').select2('val', selected);
                            }
                            else {
                                $('#not-found').append('<li>' + e + ' is not monitored</li>');
                                $('#probes-not-found').show();
                            }
                        })
                        $('#loading-div-background').hide();
                        var fixedStart = false;
                        if(data.stopped_at == 'Undefined') {
                            data.stopped_at = Math.ceil(Date.now() / 1000);
                            fixedStart = true
                        }
                        modifyPeriod(data.started_at, data.stopped_at);
                        if(fixedStart) {
                            startRefreshingFixedStart();
                        }
                        $('.active').removeClass('active');
                    },
                    timeout: 10000,
                    error: function(jqXHR, status, errorThrown) {
                        alert('Timeout or Error occured');
                        $('#loading-div-background').hide();
                    }
                });
            }

            function selectAll() {
                $('.activable').addClass('active');
                startRefreshing();
                deselectAll();
                var selected = [];
                $('select option').each(function(i, e) {
                    selected[selected.length] = $(e).attr('value');
                    $('select').trigger({
                        type: 'select2-selecting',
                        val: $(e).attr('value')
                    });
                });
                $('select').select2('val', selected);
                $('#summary').attr('src', "{{ url_for('v1.send_summary_graph', start=start, end=end, metric=metric) }}");
                reloadAllImages('last');
                $('#zip').text('Download all probes RRD');
            }

            function deselectAll() {
                $('.activable').addClass('active');
                startRefreshing();
                $('select').each(function () {
                    $(this).select2('val', '');
                });
                var selected = [];
                $('select option').each(function(i, e) {
                    selected[selected.length] = $(e).attr('value');
                    $('select').trigger({
                        type: 'select2-removing',
                        val: $(e).attr('value')
                    });
                });
                $('#summary').attr('src', "{{ url_for('v1.send_summary_graph', start=start, end=end, metric=metric) }}");
                reloadAllImages('last');
                $('#probes-not-found').hide();
                $('#not-found').empty();
                $('#zip').text('Download all probes RRD');
            }

            function probeInSelect(probe) {
                var found = false;
                probeSplit = probe.split('-');
                probeBase = probeSplit[0];
                probeNum = probeSplit[probeSplit.length-1];
                $('select option').each(function(i, e) {
                    multiProbeSplit = $(e).attr('value').split('-');
                    multiProbeBase = multiProbeSplit[0];
                    while((elem=multiProbeSplit.pop()) != null) {
                        if(probeBase == multiProbeBase && probeNum == elem) {
                            found = $(e).attr('value');
                        }
                    }
                });
                return found;
            }

            function multiprobes_alert() {
                alert("Some of your graphs include more than one probe!");
            }

            $(function() {
                $('#zip').click(function(){
                    //$(this).attr('href', "{{ url_for('v1.send_zip') }}?probes=" + $('select').select2('val'));
                    alert("Service not available.");
                });
            });

            $(document).ready(function () {
                startRefreshing();

                $('#job-field').numeric({decimal: false, negative: false});

                $('#loading-div-background').css({opacity: 0.75});

                // Init select probe list
                var cookie = $.cookie("probes_{{ hostname.capitalize() }}");
                if(!cookie) {
                    var probes = [];
                } else {
                    var probes = JSON.parse(cookie);
                }
                $('select').select2({
                    placeholder: 'Select probes'
                });
                $('select').select2('val', probes);

                // Event handler for adding a probe
                $(document.body).on('select2-selecting', 'select', function(e) {
                  $('.activable').addClass('active');
                    var on_error_file = "{{ url_for("v1.static", filename="not_found.gif") }}"
                    var probe = '<a href="{{ url_for("v1.welcome") }}{{ metric }}/probe/' + e.val + '/' + '"><img class="graph" id="' + e.val + '" src="{{ url_for("v1.welcome") }}{{ metric }}/graph/' + e.val + '/{{ start }}/{{ end }}/" alt="Graph ' + e.val + '" onerror="this.src=\'' + on_error_file.val + '\'" width="497" height="187" /></a>';
                    $('#probes').append(probe);
                    var probes = $('select').select2('val');
                    if(jQuery.inArray(e.val, $('select').select2('val')) == -1) {
                        probes.push(e.val);
                    }
                    $('#summary').attr('src', "{{ url_for('v1.send_summary_graph', start=start, end=end, metric=metric) }}?probes=" + probes);
                    $('#zip').text('Download selected probes RRD');
                    reloadAllImages('last');
                });

                // Event handler for deleting a probe
                $(document.body).on('select2-removing', 'select', function(e) {
                    $('.activable').addClass('active');
                    $('#' + e.val.replace(/\./g, '\\.')).parent().remove();
                    if($('select').select2('val') == '') {
                        $('#zip').text('Download all probes RRD');
                        $('#summary').attr('src', "{{ url_for('v1.send_summary_graph', start=start, end=end, metric=metric) }}");
                    } else {
                        $('#zip').text('Download selected probes RRD');
                        $('#summary').attr('src', "{{ url_for('v1.send_summary_graph', start=start, end=end, metric=metric) }}?probes=" + $('select').select2('val'));
                    }
                    reloadAllImages('last');
                });

                // Bind buttons to event handlers
                $('#job-button').click(selectJobId);
                $('#select-all').click(selectAll);
                $('#deselect-all').click(deselectAll);

                // Display the graph for each preselected probes
                $.each(probes, function(index, value) {
                    $('select').trigger({
                        type: 'select2-selecting',
                        val: value
                    });
                });

                // Display alert if multiprobes
                {% with messages = get_flashed_messages() %}
                  {% if messages %}
                      {% for message in messages %}
                      multiprobes = true;
                      {% endfor %}
                  {% endif %}
                {% endwith %}
       
                if(multiprobes){
                    multiprobes_alert();
                }

                {% if view == 'scale' %}
                    // Set a cookie storing the probe list
                    $(window).unload(function() {
                        var value = $('select').val();
                        if(value == null) {
                          $.removeCookie("probes_{{ hostname.capitalize() }}", {path: '/'});
                        } else {
                        $.cookie("probes_{{ hostname.capitalize() }}", JSON.stringify(value), {path: '/'});
                        }
                    });
                {% endif %}
            });

        </script>
    </head>
    <body>
        <div id="header"><h1>{{ hostname.capitalize() }} monitoring</h1></div>
        <!-- Horizontal menu bar -->
        <div id="cssmenu">
            <ul>
                {% if metric == 'energy' %}
                <li class="active has-sub"><a class="activable" href="{{ url_for('v1.welcome_scale', metric='energy', scale='minute') }}"><span>Energy</span></a>
                {% else %}
                <li class="has-sub"><a class="activable" href="{{ url_for('v1.welcome_scale', metric='energy', scale='minute') }}"><span>Energy</span></a>
                {% endif %}
                <ul>
                {% for label in scales %}
                    {% if metric == 'energy' and label == scale %}
                        <li class="active"><a class="active activable" href="{{ url_for('v1.welcome_scale', metric='energy', scale=label) }}"><span>{{ label }}</span></a></li>
                        {% set metric = 'energy' %}
                    {% else %}
                        <li><a href="{{ url_for('v1.welcome_scale', metric='energy', scale=label) }}"><span>{{ label }}</span></a></li>
                    {% endif %}
                {% endfor %}
                </ul>
                </li>
                {% if metric == 'network' %}
                <li class="active has-sub"><a class="activable" href="{{ url_for('v1.welcome_scale', metric='network', scale='minute') }}"><span>Network</span></a>
                {% else %}
                <li class="has-sub"><a class="activable" href="{{ url_for('v1.welcome_scale', metric='network', scale='minute') }}"><span>Network</span></a>
                {% endif %}
                <ul>
                {% for label in scales %}
                    {% if metric == 'network' and label == scale %}
                        <li class="active"><a class="active activable" href="{{ url_for('v1.welcome_scale', metric='network', scale=label) }}"><span>{{ label }}</span></a></li>
                        {% set metric = 'network' %}
                    {% else %}
                        <li><a href="{{ url_for('v1.welcome_scale', metric='network', scale=label) }}"><span>{{ label }}</span></a></li>
                    {% endif %}
                {% endfor %}
                </ul>
                </li>
            </ul>
        </div>
       <div id="inner">
            <!-- Period view (all probes for one period) -->
            {% if view == 'scale' %}
                {% if probes|count > 0 %}
                    <h2>Summary</h2>
                    <!-- Display summary graph -->
                    <img class="graph" id="summary" src="{{ url_for('v1.send_summary_graph', metric=metric, start=start, end=end) }}" alt="Summary graph" onerror="this.src='{{ url_for('v1.static', filename='not_found.gif') }}'" width="694" height="261" />
                    <h2>Details</h2>
                    <!-- Display all probe graphs -->
                    <select multiple>
                    {% for probe in probes %}
                        <option value="{{ probe }}">{{ probe }}</option>
                    {% endfor %}
                    </select>
                    <input type="text" id="job-field"/><button type="button" id="job-button">Job</button>
                    <button type="button" id="select-all">All</button>
                    <button type="button" id="deselect-all">Clear</button>
                    <!-- <a style="float:right; margin-top:10px" id="zip" href="{{ url_for('v1.send_zip') }}">Download all probes RRD</a> -->
                    <div id="probes"></div>
                    <div id="probes-not-found" style="display:none">Probes not found:
                        <ul id="not-found"></ul>
                    </div>
                {% else %}
                    <p>No probes found.</p>
                {% endif %}

            <!-- Probe view (all scales for one probe) -->
            {% elif view == 'probe' %}
                <h2>{{ probe }} <!-- <a style="float:right" href="{{ url_for('v1.send_zip') }}?probes={{ probe }}">Download RRD</a> --></h2>
                {% for scale in scales %}
                    <img class="graph" src="{{ url_for('v1.send_probe_graph', metric=metric, probe=probe, start=scales[scale]['start'], end=scales[scale]['end'])}}" alt="Graph {{ probe }}" onerror="this.src='{{ url_for('v1.static', filename='not_found.gif') }}'" width="497" height="187" />
                {% endfor %}
            {% endif %}
        </div>
        <div id="loading-div-background">
            <div id="loading-div">
                <h2>Please wait...</h2>
            </div>
        </div>
    </body>
</html>
