{#
/**
 * 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 Summary" %} | {% endblock %}

{% block actionMenu %}
    {% include "report-schedule-buttons.twig" %}
{% endblock %}

{% block pageContent %}

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

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

        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-refresh-on-form-submit="false">
                <div class="XiboFilterCustom">
                    <div class="FilterDiv card-body" id="timeDisconnectedReport">
                        <form class="form-inline">
                            {% set title %}{% trans "Range" %}{% endset %}
                            {{ inline.dateRangeFilter("reportFilter", title, "", "", "", "", "") }}

                            {% set title %}{% trans "Group By" %}{% endset %}
                            {% set options = [
                                { id: "display", name: "Display"|trans },
                                { id: "displayGroup", name: "Display Group"|trans },
                            ] %}
                            {{ inline.dropdown("groupBy", "single", title, "", options, "id", "name", "") }}

                            {% set title %}{% trans "Display" %}{% endset %}
                            {% set attributes = [
                                { name: "data-width", value: "200px" },
                                { name: "data-allow-clear", value: "true" },
                                { name: "data-placeholder--id", value: null },
                                { name: "data-placeholder--value", value: "" },
                                { name: "data-search-url", value: url_for("display.search") },
                                { name: "data-search-term", value: "display" },
                                { name: "data-search-term-tags", value: "tags" },
                                { name: "data-id-property", value: "displayId" },
                                { name: "data-text-property", value: "display" }
                            ] %}
                            {{ inline.dropdown("displayId", "single", title, "", null, "displayId", "display", "", "pagedSelect", "", "d", "", attributes) }}

                            {% set title %}{% trans "Display Group" %}{% endset %}
                            {% set attributes = [
                                { name: "data-width", value: "200px" },
                                { name: "data-allow-clear", value: "true" },
                                { name: "data-placeholder--id", value: null },
                                { name: "data-placeholder--value", value: "" },
                                { name: "data-search-url", value: url_for("displayGroup.search") },
                                { name: "data-search-term", value: "displayGroup" },
                                { name: "data-id-property", value: "displayGroupId" },
                                { name: "data-text-property", value: "displayGroup" }
                            ] %}
                            {{ inline.dropdown("displayGroupId[]", "dropdownmulti", title, "", null, "displayGroupId", "displayGroup", "", "pagedSelect", "", "d", "", attributes) }}

                            {% if currentUser.featureEnabled("tag.tagging") %}
                                {% set title %}{% trans "Tags" %}{% endset %}
                                {% set exactTagTitle %}{% trans "Exact match?" %}{% endset %}
                                {% set logicalOperatorTitle %}{% trans "When filtering by multiple Tags, which logical operator should be used?" %}{% endset %}
                                {% set helpText %}{% trans "A comma separated list of tags to filter by. Enter --no-tag to see items without tags." %}{% endset %}
                                {{ inline.inputWithTags("tags", title, null, helpText, null, null, null, "exactTags", exactTagTitle, logicalOperatorTitle) }}
                            {% endif %}

                            {% set title %}{% trans "Only show currently logged in?" %}{% endset %}
                            {{ inline.checkbox("onlyLoggedIn", title) }}

                            <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>

                <!-- Card Header -->
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="chart-tab" data-toggle="tab" href="#chartTab" role="tab"
                               aria-controls="chartTab" aria-selected="true">Chart</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="tabular-tab" data-toggle="tab" href="#tabularTab" role="tab"
                               aria-controls="tabularTab" aria-selected="false">Tabular</a>
                        </li>
                    </ul>
                </div>

                <!-- Card Body -->
                <div class="card-body">
                    <div class="tab-content">
                        <!-- CHART TAB-->
                        <div class="tab-pane active" id="chartTab" role="tabpanel" aria-labelledby="chart-tab">
                            <div class="chart-container" style="height:550px;">
                                <canvas id="canvas" style="clear:both; margin-top:25px;" height="70%"></canvas>
                            </div>
                        </div>

                        <!-- TABULAR TAB-->
                        <div class="tab-pane show" id="tabularTab" role="tabpanel" aria-labelledby="tabular-tab">
                            <!-- DATATABLE -->
                            <div class="table-container" id="table_wrapper">
                                <table id="timeDisconnectedTbl"
                                       class="table xibo-table table-striped table-full-width"
                                       style="width: 100%"
                                       data-url="/report/data/timedisconnectedsummary"
                                >
                                    <thead>
                                    <tr>
                                        <th>{% trans "Display ID" %}</th>
                                        <th>{% trans "Display" %}</th>
                                        <th>{% trans "Display Group ID" %}</th>
                                        <th>{% trans "Display Group" %}</th>
                                        <th>{% trans "Time Disconnected" %}</th>
                                        <th>{% trans "Time Connected" %}</th>
                                        <th>{% trans "Average Time Disconnected" %}</th>
                                        <th>{% trans "Average Time Connected" %}</th>
                                        <th>{% trans "Availability" %}</th>
                                        <th>{% trans "Units" %}</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                    <tfoot>
                                    <tr>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                        <th></th>
                                    </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>


                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

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

        $(document).ready(function() {

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

            let $report = $("#timeDisconnectedReport");
            let $dataTable = $('#timeDisconnectedTbl'); // Datatable
            let chart = null;
            let result; // XHR get data result

            let imageLoader = $("#imageLoader");
            let $warning = $("#applyWarning");
            let $applyBtn = $("#applyBtn");

            // Initialize table with empty data
            let table = $dataTable.DataTable({
                language: dataTablesLanguage,
                dom: dataTablesTemplate,
                searching: false,
                paging: true,
                bInfo: false,
                stateSave: true,
                bDestroy: true,
                processing: true,
                ordering: false,
                data: {},
                columns: [
                    {"data": "displayId"},
                    {"data": "display"},
                    {"data": "displayGroupId"},
                    {"data": "displayGroup"},
                    {"data": "timeDisconnected", "sortable": false},
                    {"data": "timeConnected", "sortable": false},
                    {"data": "avgTimeDisconnected", "sortable": false},
                    {"data": "avgTimeConnected", "sortable": false},
                    {"data": "availabilityPercentage", "sortable": false},
                    {"data": "postUnits", "sortable": false},
                ],
                drawCallback: function () {
                    if ($('select[name="groupBy"]').val() === 'displayGroup') {
                        // Hide 'Display ID and Display' columns
                        $(this.api().columns([0, 1]).visible(false));
                        $(this.api().columns([2, 3, 6, 7]).visible(true));
                    } else {
                        // Hide 'Display Group ID, Display Group, Avg Time Connected/Disconnected' columns
                        $(this.api().columns([2, 3, 6, 7]).visible(false));
                        $(this.api().columns([0, 1]).visible(true));
                    }
                },
            });

            // Get Data
            function getData(url) {
                $.ajax({
                    url: url,
                    method: 'GET',
                    dataType: 'json',
                    data: $report.find("form").serialize(),
                    success: function success(data) {
                        result = data;
                        $applyBtn.removeClass('disabled');
                        imageLoader.removeClass('fa fa-spinner fa-spin loading-icon');

                        // Based on tab load data
                        if ($('.nav-tabs .nav-item a.active').attr("href") === '#tabularTab') {
                            setTabularData(table, result.table);
                        } else {
                            setChartData(result.chart);
                        }
                    },
                    error: function error(xhr, textStatus, _error) {
                        $applyBtn.removeClass('disabled');
                        toastr.error(xhr.responseJSON.message);
                    }
                });
            }

            function setTabularData(table, data) {
                table.clear().draw();

                if (Object.keys(data).length > 0) {
                    table.rows.add( data ).draw()
                }
            }

            function setChartData(data) {

                setTimeout(function() {
                    $applyBtn.removeClass('disabled');
                }, 300);

                if (chart !== undefined && chart !== null) {
                    chart.destroy();
                }

                // Create our chart
                chart = new Chart($("#canvas"), data);
            }

            // Tab shown/click load relevant table/chart
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                let activeTab = $(e.target).attr("href")
                if (result) {
                    if (activeTab === '#tabularTab') {
                        setTabularData(table, result.table);
                    } else {
                        setChartData(result.chart);
                    }
                }
            });

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

            // If we select a displayId we hide the display group filter
            $('#displayId').off('change').change( function() {

                let displayId = $('#displayId').val();
                if (displayId) {
                    $('select[name="displayGroupId[]"] option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().hide();
                    $('select[name="groupBy[]"] option').remove();
                    $('select[name="groupBy"]').parent().hide();
                } else {
                    $('#displayId option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().show();
                    $('select[name="groupBy"]').parent().show();
                }
            });

            $("#refreshGrid").click(function () {
                table.ajax.reload();
            });
        });

        function timeDisconnectedScheduleCallback(dialog) {

            // If we select a displayId we hide the display group filter
            $('#reportScheduleAddForm #displayId').off('change').change( function() {

                let displayId = $('#reportScheduleAddForm #displayId').val();
                if (displayId) {
                    $('select[name="displayGroupId[]"] option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().parent().hide();
                    $('select[name="groupBy[]"] option').remove();
                    $('select[name="groupBy"]').parent().hide();
                } else {
                    $('#reportScheduleAddForm #displayId option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().parent().show();
                    $('select[name="groupBy"]').parent().show();
                }
            });
        }

    </script>
{% endblock %}