{#
/*
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2021 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: Proof of Play" %} | {% endblock %}

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

{% block pageContent %}

    <div class="widget">
        <div class="widget-title">
            <span>{% trans "Proof of Play" %}</span>
        </div>

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

        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-grid-name="proofOfPlayView" data-refresh-on-form-submit="false">
                <div class="XiboFilterCustom card bg-light mb-3">
                    <div class="FilterDiv card-body" id="proofofplayReport">
                        <!-- Form Filter -->
                        <form class="form-inline">
                            {% set title %}{% trans "Range" %}{% 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 "Time" %}{% endset %}
                            {{ inline.time("statsFromDtTime", title, "00:00", "", "stats-from-dt-time") }}

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

                            {% set title %}{% trans "Time" %}{% endset %}
                            {{ inline.time("statsToDtTime", title, "00:00", "", "stats-to-dt-time") }}

                            {% set title %}{% trans "Group By" %}{% endset %}
                            {% set options = [
                                { id: "display", name: "Display" },
                                { id: "displayGroup", name: "Display Group"|trans },
                                { id: "tag", name: "Tag"|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) }}

                            {% 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" }
                            ] %}

                            {% set title %}{% trans "Layout" %}{% endset %}
                            {{ inline.dropdown("layoutId[]", "dropdownmulti", title, "", null, "layoutId", "layout", "", "pagedSelect", "", "l", "", attributes) }}

                            {# Campaign list only. #}
                            {% set attributes = [
                                { name: "data-search-url", value:  url_for("campaign.search") },
                                { name: "data-width", value: "200px" },
                                { name: "data-allow-clear", value: "true" },
                                { name: "data-placeholder--id", value: null },
                                { name: "data-placeholder--value", value: "" },
                            ] %}

                            {% set title %}{% trans "Campaign" %}{% endset %}
                            {% set helpText %}{% trans "Please select a Campaign" %}{% endset %}
                            {{ inline.dropdown("parentCampaignId", "single", title, "", null, "campaignId", "campaign", "", "", "", "", "", attributes) }}

                            {% 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-search-term-tags", value: "tags" },
                                { name: "data-id-property", value: "mediaId" },
                                { name: "data-text-property", value: "name" }
                            ] %}
                            {% set title %}{% trans "Media" %}{% endset %}
                            {{ inline.dropdown("mediaId[]", "dropdownmulti", title, "", null, "mediaId", "name", "", "pagedSelect", "", "m", "", attributes) }}

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

                            {% set title %}{% trans "Tags from" %}{% endset %}
                            {% set dg %}{% trans "Display" %}{% endset %}
                            {% set layout %}{% trans "Layout" %}{% endset %}
                            {% set media %}{% trans "Media" %}{% endset %}
                            {% set options = [
                                { tagsTypeid: "dg", tagsType: dg },
                                { tagsTypeid: "layout", tagsType: layout },
                                { tagsTypeid: "media", tagsType: media }
                            ] %}
                            {{ inline.dropdown("tagsType", "single", title, "dg", options, "tagsTypeid", "tagsType") }}

                            {% if currentUser.featureEnabled("tag.tagging") %}
                                {% set title %}{% trans "Tags" %}{% endset %}
                                {% set exactMatchTitle %}{% trans "Should Tags filter by 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 a tag|tag value to filter tags with values. Enter --no-tag to filter all items without tags. Enter - before a tag or tag value to exclude from results." %}{% endset %}
                                {{ inline.inputWithTags("tags", title, null, helpText, null, null, null, "exactTags", exactMatchTitle, logicalOperatorTitle) }}
                            {% endif %}

                            <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="tabular-tab" data-toggle="tab" href="#tabularTab" role="tab"
                               aria-controls="tabularTab" aria-selected="true">Tabular</a>
                        </li>
                    </ul>
                </div>

                <!-- Card Body -->
                <div class="card-body">
                    <div class="tab-content">
                        <!-- TABULAR TAB-->
                        <div class="tab-pane active" id="tabularTab" role="tabpanel" aria-labelledby="tabular-tab">
                            <!-- DATATABLE -->
                            <div class="table-container" id="table_wrapper">
                                <table id="stats"
                                       class="table xibo-table table-striped table-full-width"
                                       style="width: 100%"
                                       data-state-preference-name="proofOfPlayGrid"
                                       data-url="/report/data/proofofplayReport">
                                    <thead>
                                    <tr>
                                        <th>{% trans "Type" %}</th>
                                        <th>{% trans "Display ID" %}</th>
                                        <th>{% trans "Display" %}</th>
                                        <th>{% trans "Display Group ID" %}</th>
                                        <th>{% trans "Display Group" %}</th>
                                        <th>{% trans "Tag ID" %}</th>
                                        <th>{% trans "Tag Name" %}</th>
                                        <th>{% trans "Campaign" %}</th>
                                        <th>{% trans "Layout ID" %}</th>
                                        <th>{% trans "Layout" %}</th>
                                        <th>{% trans "Widget ID" %}</th>
                                        <th>{% trans "Media" %}</th>
                                        <th>{% trans "Tag" %}</th>
                                        <th>{% trans "Number of Plays" %}</th>
                                        <th>{% trans "Total Duration" %}</th>
                                        <th>{% trans "Total Duration (s)" %}</th>
                                        <th title="{{ "NB: proof of play records which span your range are returned in this report."|trans }}">{% trans "First Period Shown" %}</th>
                                        <th title="{{ "NB: proof of play records which span your range are returned in this report."|trans }}">{% trans "Last Period Shown" %}</th>
                                    </tr>
                                    </thead>
                                    <tbody>

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

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

            // Report Filter
            let reportFilter = $("#reportFilter"); // Report Filter

            // Grid
            let table = $dataTable.DataTable({
                "language": dataTablesLanguage,
                dom: dataTablesTemplate,
                stateSave: true,
                stateDuration: 0,
                stateLoadCallback: dataTableStateLoadCallback,
                stateSaveCallback: dataTableStateSaveCallback,
                drawCallback: function( settings ) {
                    setTimeout(function() {
                        $("#applyBtn").removeClass('disabled');
                    }, 300);

                    // We hide empty columns and display appropriate columns (ie ID and name)
                    switch ($('select[name="groupBy"]').val()) {
                        case 'displayGroup':
                            $(this.api().columns([1, 2, 5, 6]).visible(false));
                            $(this.api().columns([3, 4]).visible(true));
                            break;
                        case 'tag':
                            $(this.api().columns([1,2, 3, 4]).visible(false));
                            $(this.api().columns([5, 6]).visible(true));
                            break;
                        default:
                            $(this.api().columns([3, 4, 5, 6]).visible(false));
                            $(this.api().columns([1, 2]).visible(true));
                    }
                },
                filter: false,
                "order": [[1, "asc"]],
                data:{},
                "columns": [
                    {"data": "type"},
                    {"data": "displayId"},
                    {"data": "display"},
                    {"data": "displayGroupId"},
                    {"data": "displayGroup"},
                    {"data": "tagId"},
                    {"data": "tagName"},
                    {"data": "parentCampaign"},
                    {"data": "layoutId"},
                    {"data": "layout"},
                    {"data": "widgetId"},
                    {"data": "media"},
                    {"data": "tag"},
                    {"data": "numberPlays"},
                    {
                        "data": "duration",
                        "render": function (data, type, row, meta) {
                            if (type != "display")
                                return "";

                            var durationData = moment.duration(data, "seconds");
                            var dataM = '';

                            var months = durationData.months();
                            if (months > 0) {
                                durationData.subtract(moment.duration(months,'months'));
                                dataM += months + '{% trans "month" %} ';
                            }

                            var days = durationData.days();
                            durationData.subtract(moment.duration(days,'days'));
                            dataM += days + '{% trans "day" %} ';

                            var hours = durationData.hours();
                            durationData.subtract(moment.duration(hours,'hours'));
                            dataM += hours + '{% trans "hr" %} ';

                            var minutes = durationData.minutes();
                            durationData.subtract(moment.duration(minutes,'minutes'));
                            dataM += minutes + '{% trans "min" %} ';

                            var seconds = durationData.seconds();
                            dataM += seconds + '{% trans "sec" %} ';

                            return  dataM;
                        }
                    },
                    {"data": "duration"},
                    {"data": "minStart"},
                    {"data": "maxEnd"}
                ],
                footerCallback: function (row, data, start, end, display) {
                    let api = this.api();

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

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

            // table.on('draw', dataTableDraw);
            // table.on('processing.dt', dataTableProcessing);
            // dataTableAddButtons(table, $('#stats_wrapper').find('.dataTables_buttons'));

            // Get Data
            function getData(url) {

                $.ajax({
                    url: url,
                    method: 'GET',
                    dataType: 'json',
                    data: $("#stats").closest(".XiboGrid").find(".FilterDiv form").serializeObject(),
                    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);
                    }
                }
            });

            table.on('draw', dataTableDraw);
            table.on('processing.dt', dataTableProcessing);
            dataTableAddButtons(table, $('#stats_wrapper').find('.dataTables_buttons'));

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

            // If we select a groupBy data, we hide the display filter
            $("select[name='groupBy']").on('change', function() {
                let optionSelected = $(this).find("option:selected").val();

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

                if (optionSelected === 'display') {
                    $("select[name='displayId']").parent().show();
                } else {
                    $("select[name='displayId']").parent().hide();
                }
            });

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

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

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

                let anchorReportAddBtn = $("button#reportAddBtn");
                let type = $("#type").val();
                let tagsType = $("#tagsType").val();
                let tags = $("#tags").val();
                let exactTags = $('#exactTags').is(":checked");

                anchorReportAddBtn.attr("href", "{{ url_for("reportschedule.add.form") }}?type=" + type + "&tagsType=" + tagsType + "&tags=" + tags + "&exactTags=" + exactTags
                    + "&reportName=proofofplayReport" );

            };

            checkReportFilter(reportFilter);
            checkFilterAndApply();


            var $campaignSelect = $('#parentCampaignId');
            $campaignSelect.select2({
                ajax: {
                    url: $campaignSelect.data("searchUrl"),
                    dataType: "json",
                    delay: 250,
                    placeholder: 'Campaign',
                    allowClear: true,
                    data: function(params) {

                        var query = {
                            isLayoutSpecific: 0,
                            retired: 0,
                            totalDuration: 0,
                            name: params.term,
                            start: 0,
                            length: 10,
                            columns: [
                                {
                                    "data": "isLayoutSpecific"
                                },
                                {
                                    "data": "campaign"
                                }
                            ],
                            order: [
                                {
                                    "column": 0,
                                    "dir": "asc"
                                },
                                {
                                    "column": 1,
                                    "dir": "asc"
                                }
                            ]
                        };

                        // Set the start parameter based on the page number
                        if (params.page != null) {
                            query.start = (params.page - 1) * 10;
                        }

                        return query;
                    },
                    processResults: function(data, params) {

                        var results = [];
                        var campaigns = [];

                        $.each(data.data, function(index, element) {
                            campaigns.push({
                                "id": element.campaignId,
                                "text": element.campaign
                            });
                        });

                        results.push({
                            "text": $campaignSelect.data('transCampaigns'),
                            "children": campaigns
                        })


                        var page = params.page || 1;
                        page = (page > 1) ? page - 1 : page;

                        return {
                            results: results,
                            pagination: {
                                more: (page * 10 < data.recordsTotal)
                            }
                        }
                    }
                }
            })
        });

        function proofOfPlayScheduleCallback() {

            let $displayId = $('#proofofplayReport #displayId');
            let $layoutId = $('#proofofplayReport [id="layoutId[]"]');
            let $mediaId = $('#proofofplayReport [id="mediaId[]"]');
            let $newDisplayId = $('#proofofplayScheduleAddForm #displayId');
            let $newLayoutId = $('#proofofplayScheduleAddForm [id="layoutId[]"]');
            let $newMediaId = $('#proofofplayScheduleAddForm [id="mediaId[]"]');

            appendOptions($newDisplayId, $displayId.find('option:selected').clone());
            appendOptions($newLayoutId, $layoutId.find('option:selected').clone());
            appendOptions($newMediaId, $mediaId.find('option:selected').clone());
        }

        function appendOptions(element, options) {

            for (let i = 0; i < options.length; i++) {

                let option = options[i];
                element.append(option).trigger('change');
                $(option).prop('selected', true);
                element.trigger({
                    type: 'select2:select',
                    params: {
                        data: option
                    }
                });
            }
        }
    </script>
{% endblock %}