{#
/**
 * Copyright (C) 2020 Xibo Signage Ltd
 *
 * Xibo - Digital Signage - http://www.xibo.org.uk
 *
 * This file is part of Xibo.
 *
 * Xibo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Xibo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */
#}

{% extends "authed.twig" %}
{% import "inline.twig" as inline %}

{% block title %}{% trans "Report: Time Connected" %} | {% endblock %}

{% block actionMenu %}
    <style>
        table {
            table-layout: fixed;
            border-collapse: collapse;
            border-spacing: 20px 0;
            padding: 20px 0 0;
        }
        th {
            text-align: center;
        }
        td.display-label {
            padding-right: 10px;
            text-align: right;
        }
        td.display-percent {
            border: 1px solid #408640;
        }
        .note-box {
            height: 15px;
            width: 15px;
            float:left;
        }
    </style>
    {% include "report-schedule-buttons.twig" %}
{% endblock %}

{% block pageContent %}
    <div class="widget">
        <div class="widget-title">
            <span>{% trans "Time Connected" %}</span>
        </div>

        {% include "report-selector.twig" %}

        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-refresh-on-form-submit="false">
                <div class="pull-right p-3">
                    <div>
                        <div class="note-box" style="background-color: #03a9f4;"></div>
                        <div style="padding-left: 20px">Blue is disconnected %</div>
                    </div>
                    <div>
                        <div class="note-box" style="background-color: #5cb85c;"></div>
                        <div style="padding-left: 20px">Green is connected %</div>
                    </div>
                </div>
                <div class="XiboFilterCustom card bg-light mb-3">
                    <div class="FilterDiv card-body" id="timeconnected">
                        <form class="form-inline">
                            {% set title %}{% trans "Range" %}{% endset %}
                            {{ inline.dateRangeFilter("reportFilter", title, "", "", "", "", "") }}

                            {% set title %}{% trans "Group by" %}{% endset %}
                            {% set byhour %}{% trans "Hour" %}{% endset %}
                            {% set bydayofmonth %}{% trans "Day of month" %}{% endset %}
                            {% set options = [
                                { filterName: "byhour", groupByFilter: byhour },
                                { filterName: "bydayofmonth", groupByFilter: bydayofmonth },
                            ] %}
                            {{ inline.dropdown("groupByFilter", "single", title, "", options, "filterName", "groupByFilter", "", "group-by-filter") }}

                            {% set title %}{% trans "Display/Display Groups" %}{% endset %}
                            {% set helpText %}{% trans "Please select one or more displays / groups for this notification to be shown on - Layouts will need the notification widget." %}{% endset %}
                            {% set attributes = [
                                { name: "data-width", value: "100%" }
                            ] %}
                            {% set transGroups %}{% trans "Groups" %}{% endset %}
                            {% set transDisplays %}{% trans "Display" %}{% endset %}
                            {% set optionGroups = [
                                {id: "group", label: transGroups},
                                {id: "display", label: transDisplays}
                            ] %}
                            {{ inline.dropdown("displayGroupId[]", "dropdownmulti", title, displayGroupIds, {group: defaults.displayGroups, display: defaults.displays}, "displayGroupId", "displayGroup", helpText, "selectPicker", "", "", "", attributes, optionGroups) }}

                            <div class="w-100">
                                <a id="applyBtn" class="btn btn-success">
                                    <span>{% trans "Apply" %}</span>
                                </a>
                                <span id="imageLoader" class=""></span>
                                <span id="applyWarning" class="text-warning" style="display:none; padding-left: 10px">{% trans "Warning: This may return a lot of data and may take several minutes to process." %}</span>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="XiboData card pt-3">
                    <table id="records_table"></table>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block javaScript %}
    <script type="text/javascript" nonce="{{ cspNonce }}">

        $(function () {
            $('[data-toggle="popover"]').popover();
        });

        let imageLoader = $("#imageLoader");

        function setReport() {
            $("#records_table").empty();
            $.ajax({
                type: "get",
                url: "{{ url_for("report.data", {name: reportName}) }}",
                cache: false,
                dataType: "json",
                data: $("#timeconnected").find("form").serialize(),
                success: function(response) {

                    setTimeout(function() {
                        $("#applyBtn").removeClass('disabled');
                        imageLoader.removeClass('fa fa-spinner fa-spin loading-icon');
                    }, 300);


                    $('.XiboData').find(".form-error").remove();
                    if (response.success === false) {
                        $('.XiboData').append('<div class="alert alert-danger form-error">'+ response.message +'</div>');
                        return;
                    }

                    $.each(response.table.timeConnected, function(index, displayStat) {
                        var $displayHeader = $('<tr>');
                        $.each(response.table.displays[index], function(i, displayName) {
                            $displayHeader.append($('<th colspan="2">').text(displayName));
                            $displayHeader.appendTo('#records_table').html();
                        });

                        // Display Statistics
                        $.each(displayStat, function(periodId, item) {
                            var $tr = $('<tr>');

                            $.each(item, function(displayId, displayData) {

                                var percent= '';
                                if (displayData.percent > 0) {
                                    percent = Math.round((displayData.percent + Number.EPSILON) * 100) / 100 + "%";
                                }

                                var $label = $('<td class="display-label" style="width:300px">').text(displayData.label);
                                var $percentage = $('<td class="display-percent" style="width:300px">').css({"background-color": "#03a9f4",  "color": "white"}).append(
                                    $('<div>').css({"background-color": "#5cb85c", "width": percent}).text(percent)
                                );

                                $tr.append($label);
                                $tr.append($percentage);
                            });

                            $tr.appendTo('#records_table').html();
                        });
                    });
                }
            });
        }

        $(document).ready(function() {

            // Init
            var applyBtn = $("#applyBtn");

            // Enable/Disable Schedule Btn
            var checkEnableSchedule = function() {

                // Schedule button enable/disable - start
                var anchorReportAddBtn = $("button#reportAddBtn");

                anchorReportAddBtn.attr("href", "{{ url_for("reportschedule.add.form") }}?reportName=timeconnected" );
            };


            // Report Filter
            checkEnableSchedule();

            // Bind to form change
            $("#timeconnected").on('change', function() {
                checkEnableSchedule();
            });

            // Apply
            applyBtn.click(function () {
                $(this).addClass('disabled');
                imageLoader.addClass('fa fa-spinner fa-spin loading-icon');
                setReport();
            });
        });

    </script>
{% endblock %}