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

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

{% block pageContent %}

    <div class="widget">
        <div class="widget-title">
            <span>{% trans "Bandwidth" %}</span>
        </div>

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

        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-refresh-on-form-submit="false">
                <div class="XiboFilterCustom card bg-light mb-3">
                    <div class="FilterDiv card-body" id="bandwidthReport">
                        <!-- Form Filter -->
                        <form class="form-inline">
                            {% set title %}{% trans "From Date" %}{% endset %}
                            {{ inline.dateMonth("bandwidthFromDt", title, defaults.toDate, "", "", "", "") }}

                            {% set title %}{% trans "To Date" %}{% endset %}
                            {{ inline.dateMonth("bandwidthToDt", title, defaults.toDate, "", "", "", "") }}

                            {% 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) }}

                            <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="bandwidthTbl"
                                       class="table xibo-table table-striped table-full-width"
                                       style="width: 100%"
                                       data-url="/report/data/bandwidth"
                                >
                                    <thead>
                                    <tr>
                                        <th></th>
                                        <th>Bandwidth</th>
                                        <th>Unit</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                    <tfoot>
                                    <tr>
                                        <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 = $("#bandwidthReport");
            let $dataTable = $('#bandwidthTbl'); // Datatable
            let chart = null; // Chart
            let result; // XHR get data result

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

            // Initialize table with empty data
            let table = $dataTable.DataTable({
                searching: false,
                paging: true,
                bInfo: false,
                stateSave: true,
                bDestroy: true,
                processing: true,
                ordering: false,
                data: {},
                columns: [
                    {
                        data: 'label',
                        'sortable': false,
                    },
                    {
                        data: 'bandwidth',
                        'sortable': false,
                    },
                    {
                        data: 'unit',
                        'sortable': false,
                    }
                ],
            });

            // 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);
            });
        });

    </script>
{% endblock %}