{#
/*
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2019 Xibo Signage Ltd
 *
 * 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: Distribution by Layout, Media or Event" %} | {% endblock %}

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

{% block pageContent %}

    <div class="widget">
        <div class="widget-title">
            <span>{% trans "Distribution by Layout, Media or Event" %}</span>
            <span class="fa fa-info-circle widget-title-info px-1" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-content="{% trans "This chart shows an aggregate duration and number of plays for the selected Layout, Media or Event. Please select your Range and Type below. Where the Range crosses period boundaries the data is aggregated into the correct period - i.e 1 week grouped by hourly produces 24 periods." %}"></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="distributionReport">
                        <!-- Form Filter -->
                        <form class="form-inline">
                            {% set title %}{% trans "Filter" %}{% endset %}
                            {% set range %}{% trans "Select a range" %}{% endset %}
                            {% set today %}{% trans "Today" %}{% endset %}
                            {% set yesterday %}{% trans "Yesterday" %}{% endset %}
                            {% set thisweek %}{% trans "This Week" %}{% endset %}
                            {% set thismonth %}{% trans "This Month" %}{% endset %}
                            {% set thisyear %}{% trans "This Year" %}{% endset %}
                            {% set lastweek %}{% trans "Last Week" %}{% endset %}
                            {% set lastmonth %}{% trans "Last Month" %}{% endset %}
                            {% set lastyear %}{% trans "Last Year" %}{% endset %}
                            {% set options = [
                                { filterName: "", reportFilter: range },
                                { filterName: "today", reportFilter: today },
                                { filterName: "yesterday", reportFilter: yesterday },
                                { filterName: "thisweek", reportFilter: thisweek },
                                { filterName: "thismonth", reportFilter: thismonth },
                                { filterName: "thisyear", reportFilter: thisyear },
                                { filterName: "lastweek", reportFilter: lastweek },
                                { filterName: "lastmonth", reportFilter: lastmonth },
                                { filterName: "lastyear", reportFilter: lastyear },
                            ] %}
                            {{ inline.dropdown("reportFilter", "single", title, "today", options, "filterName", "reportFilter") }}

                            {% set title %}{% trans "From Date" %}{% endset %}
                            {{ inline.date("statsFromDt", title, defaults.fromDateOneDay, "", "stats-from-dt", "", "") }}

                            {% set title %}{% trans "To Date" %}{% endset %}
                            {{ inline.date("statsToDt", title, defaults.toDate, "", "stats-to-dt", "", "") }}

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

                            {% set title %}{% trans "Type" %}{% endset %}
                            {% set layout %}{% trans "Layout" %}{% endset %}
                            {% set media %}{% trans "Media" %}{% endset %}
                            {% set event %}{% trans "Event" %}{% endset %}
                            {% set options = [
                                { typeid: "layout", type: layout },
                                { typeid: "media", type: media },
                                { typeid: "event", type: event },
                            ] %}
                            {{ inline.dropdown("type", "single", title, "", options, "typeid", "type") }}

                            {% set title %}{% trans "Layout" %} *{% endset %}
                            {% set helpText %}{% trans "This field is required when the Type selected is Layout" %}{% 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("layout.search") },
                                { name: "data-search-term", value: "layout" },
                                { name: "data-search-term-tags", value: "tags" },
                                { name: "data-id-property", value: "layoutId" },
                                { name: "data-text-property", value: "layout" }
                            ] %}

                            {{ inline.dropdown("layoutId", "single", title, "", null, "layoutId", "layout", helpText, "pagedSelect layout-select", "", "l", "", attributes) }}

                            {% set title %}{% trans "Media" %} *{% endset %}
                            {% set helpText %}{% trans "This field is required when the Type selected is Media" %}{% 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("library.search") },
                                { name: "data-search-term", value: "media" },
                                { name: "data-id-property", value: "mediaId" },
                                { name: "data-text-property", value: "name" }
                            ] %}
                            {{ inline.dropdown("mediaId", "single", title, "", null, "mediaId", "name", helpText, "pagedSelect media-select", "", "m", "", attributes) }}

                            {% set title %}{% trans "Tag" %} *{% endset %}
                            {% set helpText %}{% trans "This field is required when the Type selected is Event" %}{% endset %}
                            {{ inline.input("eventTag", title, "", helpText, "tag-text") }}

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

                            <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="distributionTbl"
                                       class="table xibo-table table-striped table-full-width"
                                       style="width: 100%"
                                       data-url="/report/data/distributionReport"
                                >
                                    <thead>
                                    <tr>
                                        <th>{% trans "Period" %}</th>
                                        <th>{% trans "Duration" %}</th>
                                        <th>{% trans "Count" %}</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">

        $(document).ready(function() {

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

            let $report = $("#distributionReport");
            let $dataTable = $('#distributionTbl'); // Datatable
            let chart = null; // Chart
            let result; // XHR get data result

            let imageLoader = $("#imageLoader");
            let $warning = $("#applyWarning");
            let $applyBtn = $("#applyBtn");
            let type = $("#type");
            let mediaSelect =$(".media-select");
            let layoutSelect =$(".layout-select");
            let eventTagCls =$(".tag-text");
            let reportFilter = $("#reportFilter"); // Report Filter

            // 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: 'duration',
                        'sortable': false,
                    },
                    {
                        data: 'count',
                        'sortable': false,
                    }
                ],
                footerCallback: function (row, data, start, end, display) {
                    let api = this.api();

                    // Total over all pages
                    let totalDuration = api.column(1).data().reduce(function (a, b) {
                        return a + b;
                    }, 0);
                    let totalNumberPlays = api.column(2).data().reduce(function (a, b) {
                        return a + b;
                    }, 0);
                    let totalDurationPage = api.column(1, { page: 'current'}).data().reduce(function (a, b) {
                        return a + b;
                    }, 0);
                    let totalNumberPlaysPage = api.column(2, { page: 'current'}).data().reduce(function (a, b) {
                        return a + b;
                    }, 0);

                    // Update footer
                    $(api.column(1).footer()).html(totalDurationPage + ' (' + totalDuration + ' total)');
                    $(api.column(2).footer()).html(Math.floor(totalNumberPlaysPage) + ' (' + Math.floor(totalNumberPlays) + ' total)');
                },
            });

            // 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');
                checkFilterAndApply();

                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();
                } else {
                    $('#displayId option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().show();
                }
            });

            // Calculate the difference of number of days of a selected range
            let calculateDaysShowHideWarn = function() {

                let fromDt = moment($("#statsFromDt").val());
                let toDt = moment($("#statsToDt").val());

                let days = toDt.diff(fromDt, 'days');

                $warning.hide();
                if ( days >= 30) {
                    $warning.show();
                }

                return true;
            };

            $("#statsFromDtLink").change( function() {
                calculateDaysShowHideWarn();
            });

            $("#statsToDtLink").change( function() {
                calculateDaysShowHideWarn();
            });

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

                // Schedule button enable/disable - start
                let mediaVal = $("#mediaId").val();
                let layoutVal = $("#layoutId").val();
                let eventTagVal = $("#eventTag").val();
                let reportAddBtn = $("button#reportAddBtn");

                let typeVal = $("#type").val();

                if ( typeVal === 'layout') {
                    if (layoutVal == null) {
                        reportAddBtn.addClass('disabled');
                        reportAddBtn.removeAttr('href');
                    } else {
                        reportAddBtn.removeClass('disabled');
                        reportAddBtn.attr("href", "{{ url_for("reportschedule.add.form") }}?type=" + typeVal + "&layoutId=" + layoutVal + "&reportName=distributionReport" );
                        reportAddBtn.removeAttr('title');

                    }
                } else if ( typeVal === 'media') {
                    if (mediaVal == null) {
                        reportAddBtn.addClass('disabled');
                        reportAddBtn.removeAttr('href');
                    } else {
                        reportAddBtn.removeClass('disabled');
                        reportAddBtn.attr("href", "{{ url_for("reportschedule.add.form") }}?type=" + typeVal + "&mediaId=" + mediaVal + "&reportName=distributionReport" );
                        reportAddBtn.removeAttr('title');

                    }
                } else if ( typeVal === 'event') {
                    if (eventTagVal == null) {
                        reportAddBtn.addClass('disabled');
                        reportAddBtn.removeAttr('href');
                    } else {
                        reportAddBtn.removeClass('disabled');
                        reportAddBtn.attr("href", "{{ url_for("reportschedule.add.form") }}?type=" + typeVal + "&eventTag=" + eventTagVal + "&reportName=distributionReport" );
                        reportAddBtn.removeAttr('title');

                    }
                }
            };

            // Hide / Show FromDt and ToDt
            function checkReportFilter(reportFilter) {
                if (reportFilter.val() === '' || reportFilter.val() === undefined) {
                    $(".stats-from-dt").show();
                    $(".stats-to-dt").show();
                } else {
                    $(".stats-from-dt").hide();
                    $(".stats-to-dt").hide();
                }
            }

            let checkFilterAndApply = function() {

                reportFilter.off('change').change( function() {

                    let value = reportFilter.val();

                    // Hide / Show FromDt and ToDt
                    checkReportFilter(reportFilter);

                    // Hide / Show Warning
                    $warning.hide();
                    if ( value === '') {
                        calculateDaysShowHideWarn();
                    } else if ( value === 'thismonth' || value === 'lastmonth' || value === 'thisyear' || value === 'lastyear') {
                        $warning.show();
                    }

                });

                type.off('change').change( function() {

                    let value = type.val();
                    if (value === 'media') {
                        // show media and clear/hide the layout
                        $("#layoutId").val("");
                        $("#layoutId option").remove();
                        layoutSelect.hide();

                        $("#eventTag").val("");
                        eventTagCls.hide();

                        mediaSelect.show();


                    } else if (value === 'layout') {
                        // show layout and clear/hide the media
                        $("#mediaId").val("");
                        $("#mediaId option").remove();
                        mediaSelect.hide();

                        $("#eventTag").val("");
                        eventTagCls.hide();

                        layoutSelect.show();

                    } else if (value === 'event') {
                        // clear/hide the media and layout
                        $("#mediaId").val("");
                        $("#mediaId option").remove();
                        $("#layoutId").val("");
                        $("#layoutId option").remove();
                        mediaSelect.hide();
                        layoutSelect.hide();

                        // show tag
                        eventTagCls.show();

                    }
                });

            };

            type.val('layout');
            mediaSelect.hide();
            eventTagCls.hide();

            checkReportFilter(reportFilter);
            checkFilterAndApply();

            $applyBtn.addClass('disabled');
            checkEnableSchedule();

            // Bind to form change
            $report.on('change', function() {
                checkEnableSchedule();

                let layoutVal =  $("#layoutId").val();
                let mediaVal =  $("#mediaId").val();
                let eventVal =  $("#eventTag").val();

                if ((layoutVal === null || layoutVal === '' || layoutVal === undefined) &&
                    (mediaVal === null || mediaVal === '' || mediaVal === undefined) &&
                    (eventVal === null || eventVal === '' || eventVal === undefined) ) {
                    $applyBtn.addClass('disabled');
                } else {
                    $applyBtn.removeClass('disabled');
                }
            });
        });

        function distributionScheduleCallback(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();
                } else {
                    $('#reportScheduleAddForm #displayId option').remove();
                    $('select[name="displayGroupId[]"]').next(".select2-container").parent().parent().show();
                }
            });
        }

    </script>
{% endblock %}