{#
/**
 * Copyright (C) 2021 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 pageContent %}
    {% include "theme-dashboard-message.twig" ignore missing %}
    <div class="row">
        <div class="col-xl-3 col-md-6 col-12">
            <div class="widget">
                <div class="widget-body p-3 p-xl-2">
                    <div class="widget-icon orange pull-left">
                        <i class="fa fa-desktop"></i>
                    </div>
                    <div class="widget-content pull-left">
                        <div class="title displays-count">0</div>
                        <div class="comment displays-comment" data-title="{% trans "Display" %}" data-title-plural="{% trans "Displays" %}"></div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 col-12">
            <div class="widget">
                <div class="widget-body p-3 p-xl-2">
                    <div class="widget-icon red pull-left">
                        <i class="fa fa-tasks"></i>
                    </div>
                    <div class="widget-content pull-left">
                        <div class="title">{{ librarySize }}</div>
                        <div class="comment">{% trans "Library Size" %}</div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 col-12">
            <div class="widget">
                <div class="widget-body p-3 p-xl-2">
                    <div class="widget-icon green pull-left">
                        <i class="fa fa-users"></i>
                    </div>
                    <div class="widget-content pull-left">
                        <div class="title">{{ countUsers }}</div>
                        <div class="comment">{% if countUsers == 1 %}{% trans "User" %}{% else %}{% trans "Users" %}{% endif %}</div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 col-12">
            <div class="widget">
                <div class="widget-body p-3 p-xl-2">
                    <div class="widget-icon blue pull-left">
                        <i class="fa fa-cogs"></i>
                    </div>
                    <div class="widget-content pull-left">
                        {% if embeddedWidget != "" %}
                            {{ embeddedWidget|raw }}
                        {% else %}
                            <div class="title">{{ nowShowing }}</div>
                            <div class="comment">{% trans "Now Showing" %}</div>
                        {% endif %}
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-cloud-download"></i>
                    {% if xmdsLimit != "" %}
                        {% trans %}Bandwidth Usage. Limit {{ xmdsLimit }}{% endtrans %}
                    {% else %}
                        {% trans %}Bandwidth Usage ({{ bandwidthSuffix }}){% endtrans %}
                    {% endif %}
                    {% if currentUser.featureEnabled("displays.reporting") %}
                    <a class="pull-right" href="/report/form/bandwidth">{% trans "More Statistics" %}</a>
                    {% endif %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding">
                    <canvas id="bandwidthChart" style="clear:both;" height="230"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-tasks"></i>
                    {% if libraryLimitSet != "" %}
                        {% trans %}Library Usage. Limit {{ libraryLimit }}{% endtrans %}
                    {% else %}
                        {% trans "Library Usage" %}
                    {% endif %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding">
                    <canvas id="libraryChart" style="clear:both;" width="350" height="220"></canvas>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-desktop"></i>
                    {% trans "Display Activity" %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding">
                    <div class="table-responsive">
                        <table id="displays" class="table">
                            <thead>
                            <tr>
                                <th>{% trans "Display" %}</th>
                                <th>{% trans "Logged In" %}</th>
                                <th>{% trans "Authorised" %}</th>
                            </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="widget news-widget">
                <div class="widget-title">
                    <i class="fa fa-book"></i>
                    {% trans "Latest News" %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium">
                    {% if latestNews|length > 0 %}
                        {% for news in latestNews %}
                            <div class="article">
                                <h4 class="article_title">{{ news.title }} <small class="article_date">{{ news.date }}</small></h4>
                                <p>{{ news.description|raw }} {% if news.link %}<a href="{{ news.link }}" title="Read" target="_blank">{% trans "Full Article" %}</a>.{% endif %}</p>
                            </div>
                        {% endfor %}
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-desktop"></i>
                    {% trans "Display Status" %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding" style="overflow: hidden;">
                    <div style="text-align: center; height: 10px; margin-bottom: 5px"><span>{% trans "Click on the chart for a breakdown" %}</span></div>
                    <div style="position: relative; height: 235px">
                        <canvas id="displayStatusChart" style="clear:both;"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-cloud-download"></i>
                    {% trans "Display Content Status" %}
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding" style="overflow: hidden;">
                    <div style="text-align: center; height: 10px; margin-bottom: 5px"><span>{% trans "Click on the chart for a breakdown" %}</span></div>
                    <div style="position: relative; height: 235px">
                        <canvas id="displayContentChart" style="clear:both;"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row d-none" id="displayGroupStatusChartRow">

        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-desktop"></i>
                    <span id="dGStatusTitle">{% trans "Display Groups Status" %}</span>
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding" style="overflow: hidden;">
                    <div style="text-align: center; height: 10px; margin-bottom: 5px"><span>{% trans "Click on the chart to view Display information" %}</span></div>
                    <div style="position: relative; height: 235px;">
                        <canvas id="displayGroupStatusChart" style="clear:both;"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="widget">
                <div class="widget-title">
                    <i class="fa fa-desktop"></i>
                    <span id="dGContentTitle"> {% trans "Display Groups Content Status" %}</span>
                    <div class="clearfix"></div>
                </div>
                <div class="widget-body medium no-padding" style="overflow: hidden;">
                    <div style="text-align: center; height: 10px; margin-bottom: 5px"><span>{% trans "Click on the chart to view Display information" %}</span></div>
                    <div style="position: relative; height: 235px">
                        <canvas id="displayGroupContentStatusChart" style="clear:both;"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="widget d-none" id="displaysGridTable">
        <div class="widget-title">{% trans "Displays" %}
            {% if currentUser.featureEnabled("displays.view") %}
                <a class="pull-right" href="{{ url_for('display.view') }}">{% trans "Displays Page" %}</a>
            {% endif %}
        </div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-grid-name="displayGridView">
                <div class="XiboFilter card mb-3 bg-light d-none">
                    <div class="FilterDiv card-body" id="Filter">
                        <form class="form-inline d-block">
                            <div class="tab-content">
                                <div class="tab-pane active" id="filter-general">
                                    {{ inline.hidden("displayGroupId") }}
                                    {{ inline.hidden("mediaInventoryStatus") }}
                                    {{ inline.hidden("loggedIn") }}
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="XiboData card pt-3">
                    <table id="displaysGrid" class="table table-striped" data-state-preference-name="statusDashboardDisplays" style="width: 100%;">
                        <thead>
                        <tr>
                            <th>{% trans "ID" %}</th>
                            <th>{% trans "Display" %}</th>
                            <th>{% trans "Status" %}</th>
                            <th>{% trans "Authorised?" %}</th>
                            <th>{% trans "Current Layout" %}</th>
                            <th>{% trans "Storage Available" %}</th>
                            <th>{% trans "Storage Total" %}</th>
                            <th>{% trans "Storage Free %" %}</th>
                            <th>{% trans "Description" %}</th><th>{% trans "Orientation" %}</th>
                            <th>{% trans "Resolution" %}</th>
                            {% if currentUser.featureEnabled("tag.tagging") %}<th>{% trans "Tags" %}</th>{% endif %}
                            <th>{% trans "Default Layout" %}</th>
                            <th>{% trans "Interleave Default" %}</th>
                            <th>{% trans "Email Alert" %}</th>
                            <th>{% trans "Logged In" %}</th>
                            <th>{% trans "Last Accessed" %}</th>
                            <th>{% trans "Display Profile" %}</th>
                            <th>{% trans "Version" %}</th>
                            <th>{% trans "Device Name" %}</th>
                            <th>{% trans "IP Address" %}</th>
                            <th>{% trans "Mac Address" %}</th>
                            <th>{% trans "Timezone" %}</th>
                            <th>{% trans "Latitude" %}</th>
                            <th>{% trans "Longitude" %}</th>
                            <th>{% trans "Screen shot?" %}</th>
                            <th>{% trans "Thumbnail" %}</th>
                            <th>{% trans "CMS Transfer?" %}</th>
                            <th>{% trans "Bandwidth Limit" %}</th>
                            <th>{% trans "Last Command" %}</th>
                            <th>{% trans "XMR Registered" %}</th>
                            <th>{% trans "Commercial Licence" %}</th>
                            <th>{% trans "Remote" %}</th>
                            <th>{% trans "Created Date" %}</th>
                            <th>{% trans "Modified Date" %}</th>
                            <th>{% trans "Faults?" %}</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block javaScript %}
    <script type="text/javascript">
      const stringToColour = function(str) {
        let hash = 0;
        str.split('').forEach(char => {
          hash = char.charCodeAt(0) + ((hash << 5) - hash);
        });
        let colour = '#';
        for (let i = 0; i < 3; i++) {
          const value = (hash >> (i * 8)) & 0xff
          colour += value.toString(16).padStart(2, '0');
        }
        return colour;
      }

        var displayGroupStatusChart = null;
        var displayGroupContentStatusChart = null;

        var displayGroupId = null;
        var loggedInStatus = null;
        var mediaInventoryStatus = null;

        var displayGroupIdsContent = [];
        var displayGroupIdsStatus = [];
        var displayGridTable = null

        // Create our chart
        var bandwidthChart = new Chart($("#bandwidthChart"), {
            type: "bar",
            data: {{ bandwidthWidget|raw }},
            options: {
                scales: {
                    xAxes: [{
                        stacked: {% if xmdsLimit %}true{% else %}false{% endif %}
                    }],
                    yAxes: [{
                        scaleLabel: {
                            display: true,
                            labelString: "{{ bandwidthSuffix }}",
                        },
                        stacked: {% if xmdsLimit %}true{% else %}false{% endif %}
                    }]
                },
                legend: {
                    display: false
                },
                maintainAspectRatio: false,
            }
        });

        var libraryData = {{ libraryWidgetData|raw }};
        const libraryLabels = {{ libraryWidgetLabels|raw }};
        var colours = new Array();
        for (var i = 0; i < libraryData.length; i++) {
          colours.push(stringToColour(libraryLabels[i]));
        }
        var libraryChart = new Chart($("#libraryChart"), {
            type: 'pie',
            data: {
                datasets: [{
                    data: libraryData,
                    backgroundColor: colours
                }],
                labels: {{ libraryWidgetLabels|raw }}
            },
            options: {
                maintainAspectRatio: false
            }
        });

        $('.article_date').each(function(index, element) {
          // Replace the ISO date with a nice formatted date "for humans"
          const date = $(element).html();
          if (date) {
            $(element).html(moment(date, systemDateFormat).fromNow());
          }
        });

        var table = $("#displays").DataTable({
            "language": dataTablesLanguage,
            serverSide: true,
            stateSave: true,
            responsive: true,
            stateDuration: 0,
            stateLoadCallback: dataTableStateLoadCallback,
            stateSaveCallback: dataTableStateSaveCallback,
            filter: false,
            searchDelay: 3000,
            order: [[0, "asc"]],
            ajax: {
                "url": "{{ url_for("statusdashboard.displays") }}",
                "data": function (dataToSend) {
                    //make a new object so as not to destroy the input.
                    var data = {};
                    data.draw = dataToSend.draw;
                    data.length = dataToSend.length;
                    data.start = dataToSend.start;
                    data.order = dataToSend.order;
                    data.columns = [];

                    $.each(dataToSend.columns, function (index, e) {
                        var col = {};
                        col.data = e.data;
                        if (e.name != null && e.name !== "")
                            col.name = e.name;
                        data.columns.push(col);
                    });

                    $.extend(data, $("#displays").closest(".XiboGrid").find(".FilterDiv form").serializeObject());

                    return data;
                }
            },
            createdRow: function (row, data, index) {
                if (data.mediaInventoryStatus === 1) {
                    $(row).addClass('table-success');
                } else if (data.mediaInventoryStatus === 1) {
                    $(row).addClass('table-danger');
                } else {
                    $(row).addClass('table-warning');
                }
            },
            lengthChange: false,
            "columns": [
                {"data": "display"},
                {"data": "loggedIn", "render": dataTableTickCrossColumn},
                {"data": "licensed", "render": dataTableTickCrossColumn}
            ]
        });

        table.on('processing.dt', dataTableProcessing);
        table.on('draw', function(e, settings) {
            var $displaysComment = $(".displays-comment");
            var total = table.page.info().recordsTotal;
            $(".displays-count").html(total);
            $displaysComment.html((total > 0) ? $displaysComment.data().titlePlural : $displaysComment.data().title)
        });

        var displayData {% if displayStatus|raw %}= {{ displayStatus|raw }}{% endif %};
        var displayStatusChart = new Chart($("#displayStatusChart"), {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: displayData,
                    backgroundColor: ["rgb(0,255,0)", "rgb(255,0,0)"]
                }],
                labels: [translations.online, translations.offline]
            },
            options: {
                maintainAspectRatio: false
            }
        });

        var displayMediaStatusData {% if displayMediaStatus|raw %}= {{ displayMediaStatus|raw }}{% endif %};

        var displayContentChart = new Chart($("#displayContentChart"), {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: displayMediaStatusData,
                    backgroundColor: ["rgb(0,255,0)", "rgb(255,0,0)"]
                }],
                labels: [translations.upToDate, translations.notUpToDate]
            },
            options: {
                maintainAspectRatio: false
            }
        });

        $("#displayStatusChart").click(function(evt){
                var activePoints = displayStatusChart.getElementsAtEvent(evt);

                if (activePoints[0]) {
                    var chartData = activePoints[0]['_chart'].config.data;
                    var index = activePoints[0]['_index'];

                    var label = chartData.labels[index];

                    if (label == translations.online) {
                        loggedInStatus = 1;
                        $('#dGStatusTitle').css('color', 'rgb(0,255,0)')
                    } else {
                        loggedInStatus = 0;
                        $('#dGStatusTitle').css('color', 'rgb(255,0,0)')
                    }

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

                    $.ajax({
                        type: "get",
                        url: "{{ url_for("statusdashboard.displayGroups") }}",
                        data: {
                            status: label
                        },
                        success: function (result) {
                            if (result.success === true) {

                                var displayGroupNames = JSON.parse(result.data.displayGroupNames);
                                var displaysAssigned = JSON.parse(result.data.displayGroupMembers);
                                displayGroupIdsStatus = JSON.parse(result.data.displayGroupIds);

                                var coloursDG = [];

                                for(var i = 0; i < displayGroupNames.length; i++) {
                                    coloursDG.push($c.rand());
                                }

                                displayGroupStatusChart = new Chart($("#displayGroupStatusChart"), {
                                    type: 'doughnut',
                                    data: {
                                        datasets: [{
                                            data: displaysAssigned,
                                            backgroundColor: coloursDG
                                        }],
                                        labels: displayGroupNames
                                    },
                                    options: {
                                        maintainAspectRatio: false,
                                    }
                                });

                                $("#displayGroupStatusChartRow").removeClass('d-none');
                            }
                        }
                    });
                }
            }
        );

        $("#displayContentChart").click(function(evt){
                var activePoints = displayContentChart.getElementsAtEvent(evt);

                if (activePoints[0]) {
                    var chartData = activePoints[0]['_chart'].config.data;
                    var index = activePoints[0]['_index'];

                    var label = chartData.labels[index];

                    if (label == translations.upToDate) {
                        mediaInventoryStatus = 1;
                        $('#dGContentTitle').css('color', 'rgb(0,255,0)')
                    } else {
                        mediaInventoryStatus = -1;
                        $('#dGContentTitle').css('color', 'rgb(255,0,0)')
                    }

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

                    $.ajax({
                        type: "get",
                        url: "{{ url_for("statusdashboard.displayGroups") }}",
                        data: {
                            inventoryStatus: label
                        },
                        success: function (result) {
                            if (result.success === true) {

                                var displayGroupNames = JSON.parse(result.data.displayGroupNames);
                                var displaysAssigned = JSON.parse(result.data.displayGroupMembers);
                                displayGroupIdsContent = JSON.parse(result.data.displayGroupIds);

                                var coloursDG = [];

                                for(var i = 0; i < displayGroupNames.length; i++) {
                                    coloursDG.push($c.rand());
                                }

                                displayGroupContentStatusChart = new Chart($("#displayGroupContentStatusChart"), {
                                    type: 'doughnut',
                                    data: {
                                        datasets: [{
                                            data: displaysAssigned,
                                            backgroundColor: coloursDG
                                        }],
                                        labels: displayGroupNames
                                    },
                                    options: {
                                        maintainAspectRatio: false
                                    }
                                });

                                $("#displayGroupStatusChartRow").removeClass('d-none');
                            }
                        }
                    });
                }
            }
        );

        $("#displayGroupStatusChart").click(function(evt) {
                var activePoints = displayGroupStatusChart.getElementsAtEvent(evt);

                $('#displayGroupId').val("");
                $('#mediaInventoryStatus').val("");
                $('#loggedIn').val("");
                if (activePoints[0]) {
                    var chartData = activePoints[0]['_chart'].config.data;
                    var index = activePoints[0]['_index'];

                    displayGroupId = displayGroupIdsStatus[index];

                    $('#displayGroupId').val(displayGroupId);
                    $('#loggedIn').val(loggedInStatus);
                    handleDisplaysGrid();

                    $("#displaysGridTable").removeClass('d-none');
                }
            }
        );

        $("#displayGroupContentStatusChart").click(function(evt){
                var activePoints = displayGroupContentStatusChart.getElementsAtEvent(evt);

                if (activePoints[0]) {
                    $('#displayGroupId').val("");
                    $('#mediaInventoryStatus').val("");
                    $('#loggedIn').val("");

                    var chartData = activePoints[0]['_chart'].config.data;
                    var index = activePoints[0]['_index'];

                    displayGroupId = displayGroupIdsContent[index];

                    $('#displayGroupId').val(displayGroupId);
                    $('#mediaInventoryStatus').val(mediaInventoryStatus);
                    handleDisplaysGrid();

                    $("#displaysGridTable").removeClass('d-none');
                }
            }
        );

        function handleDisplaysGrid() {
            if (displayGridTable != null) {
                displayGridTable.ajax.reload();
            } else {
                displayGridTable = $("#displaysGrid").DataTable({
                    "language": dataTablesLanguage,
                    dom: dataTablesTemplate,
                    serverSide: true,
                    stateSave: true,
                    stateDuration: 0,
                    stateLoadCallback: dataTableStateLoadCallback,
                    stateSaveCallback: dataTableStateSaveCallback,
                    filter: false,
                    searchDelay: 3000,
                    responsive: true,
                    order: [[1, "asc"]],
                    ajax: {
                        "url": "{{ url_for("display.search") }}",
                        "data": function (dataToSend) {
                            //make a new object so as not to destroy the input.
                            var data = {};
                            data.draw = dataToSend.draw;
                            data.length = dataToSend.length;
                            data.start = dataToSend.start;
                            data.order = dataToSend.order;
                            data.columns = [];

                            $.each(dataToSend.columns, function (index, e) {
                                var col = {};
                                col.data = e.data;
                                if (e.name != null && e.name != "")
                                    col.name = e.name;
                                data.columns.push(col);
                            });

                            $.extend(data, $("#displaysGrid").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                            return data;
                        }
                    },
                    createdRow: function (row, data, index) {
                        if (data.mediaInventoryStatus === 1) {
                            $(row).addClass('table-success');
                        } else if (data.mediaInventoryStatus === 1) {
                            $(row).addClass('table-danger');
                        } else {
                            $(row).addClass('table-warning');
                        }
                    },
                    "columns": [
                        {"data": "displayId", responsivePriority: 2},
                        {"data": "display", responsivePriority: 2},
                        {
                            "data": "mediaInventoryStatus",
                            responsivePriority: 2,
                            "render": function (data, type, row) {
                                if (type != "display")
                                    return data;

                                var icon = "";
                                if (data == 1)
                                    icon = "fa-check";
                                else if (data == 2)
                                    icon = "fa-times";
                                else
                                    icon = "fa-cloud-download";

                                return '<span class="fa ' + icon + '" title="' + (row.statusDescription) + '"></span>';
                            }
                        },
                        {"data": "licensed", "render": dataTableTickCrossColumn, responsivePriority: 3},
                        {"data": "currentLayout", "visible": false, "sortable": false, responsivePriority: 5},
                        {
                            "data": "storageAvailableSpace",
                            responsivePriority: 5,
                            "visible": false,
                            "render": function (data, type, row) {
                                if (type != "display")
                                    return data;

                                return row.storageAvailableSpaceFormatted;
                            }
                        },
                        {
                            "data": "storageTotalSpace",
                            responsivePriority: 5,
                            "visible": false,
                            "render": function (data, type, row) {
                                if (type != "display")
                                    return data;

                                return row.storageTotalSpaceFormatted;
                            }
                        },
                        {"data": "storagePercentage", "visible": false, "sortable": false, responsivePriority: 5},
                        {"data": "description", "visible": false, responsivePriority: 4},
                        {"data": "orientation", "visible": false, responsivePriority: 6},
                        {"data": "resolution", "visible": false, responsivePriority: 6},
                        {% if currentUser.featureEnabled("tag.tagging") %}
                        {
                            "name": "tags",
                            responsivePriority: 3,
                            "sortable": false,
                            "visible": false,
                            "data": dataTableCreateTags
                        },
                        {% endif %}
                        {"data": "defaultLayout", "visible": false, responsivePriority: 4},
                        {"data": "incSchedule", "render": dataTableTickCrossColumn, "visible": false, responsivePriority: 5},
                        {"data": "emailAlert", "render": dataTableTickCrossColumn, "visible": false, responsivePriority: 5},
                        {"data": "loggedIn", "render": dataTableTickCrossColumn, responsivePriority: 3},
                        {"data": "lastAccessed", "render": dataTableDateFromUnix, responsivePriority: 4},
                        {
                            "name": "displayProfileId",
                            responsivePriority: 5,
                            "data": function (data, type) {
                                return data.displayProfile;
                            },
                            "visible": false
                        },
                        {
                            "name": "clientSort",
                            responsivePriority: 4,
                            "data": function (data) {
                                if (data.clientType === 'lg') {
                                    data.clientType = 'webOS'
                                }

                                return data.clientType + ' ' + data.clientVersion + '-' + data.clientCode;
                            },
                            "visible": false
                        },
                        {"data": "deviceName", "visible": false, responsivePriority: 5},
                        {"data": "clientAddress", "visible": false, responsivePriority: 6},
                        {"data": "macAddress", responsivePriority: 5},
                        {"data": "timeZone", "visible": false, responsivePriority: 5},
                        {"data": "latitude", "visible": false, responsivePriority: 6},
                        {"data": "longitude", "visible": false, responsivePriority: 6},
                        {"data": "screenShotRequested", "render": dataTableTickCrossColumn, "visible": false, "name": "screenShotRequested", responsivePriority: 7},
                        {
                            "name": "thumbnail",
                            responsivePriority: 4,
                            "orderable": false,
                            "data": function (data, type) {
                                if (type != "display")
                                    return data.thumbnail;

                                if (data.thumbnail != "") {
                                    return '<a class="display-screenshot-container" data-toggle="lightbox" data-type="image" href="' + data.thumbnail + '"><img class="display-screenshot" src="' + data.thumbnail + '" data-display-id="'+ data.displayId +'" data-type="'+ data.clientType +'" /></a>';
                                }
                                else {
                                    return "";
                                }
                            },
                            "visible": false
                        },
                        {
                            "data": "isCmsTransferInProgress",
                            "render": dataTableTickCrossColumn,
                            "visible": false,
                            "name": "isCmsTransferInProgress"
                        },
                        {
                            "name": "bandwidthLimit",
                            responsivePriority: 5,
                            "data": null,
                            "render": {"_": "bandwidthLimit", "display": "bandwidthLimitFormatted", "sort": "bandwidthLimit"},
                            "visible": false
                        },
                        {
                            "data": "lastCommandSuccess",
                            responsivePriority: 6,
                            "render": function (data, type, row) {
                                if (type != "display")
                                    return data;

                                var icon = "";
                                if (data == 1)
                                    icon = "fa-check";
                                else if (data == 0)
                                    icon = "fa-times";
                                else
                                    icon = "fa-question";

                                return "<span class='fa " + icon + "'></span>";
                            },
                            "visible": false
                        },
                        {
                            "data": "xmrChannel",
                            responsivePriority: 6,
                            "render": function (data, type, row) {
                                if (type === "export") {
                                    return (data !== null && data !== "") ? 1 : 0;
                                }

                                if (type != "display")
                                    return data;

                                var icon = "";
                                if (data != null && data != "")
                                    icon = "fa-check";
                                else
                                    icon = "fa-times";

                                return "<span class='fa " + icon + "'></span>";
                            },
                            "visible": false
                        },
                        {
                            "data": "commercialLicence",
                            "name": "commercialLicence",
                            responsivePriority: 5,
                            "render": function (data, type, row) {
                                if (type != "display")
                                    return data;

                                var icon = "";
                                if (data == 3) {
                                    return "N/A";
                                } else {
                                    if (data == 1) {
                                        icon = "fa-check";
                                    } else if (data == 0) {
                                        icon = "fa-times";
                                    } else if (data == 2) {
                                        icon = "fa-clock-o";
                                    }

                                    return '<span class="fa ' + icon + '" title="' + (row.commercialLicenceDescription) + '"></span>';
                                }
                            },
                            "visible": false
                        },
                        {
                            "name": "remote",
                            "data": null,
                            responsivePriority: 4,
                            "render": function (data, type, row) {
                                if (type === "display") {
                                    var html = "<div class='remote-icons'>";
                                    if ("{{ settings.SHOW_DISPLAY_AS_VNCLINK }}" !== "" && row.clientAddress != null && row.clientAddress !== "") {
                                        var link = "{{ settings.SHOW_DISPLAY_AS_VNCLINK }}".replace('%s', row.clientAddress);
                                        html += '<a href="' + link + '" title="{{ "VNC to this Display"|trans }}" target="{{ settings.SHOW_DISPLAY_AS_VNC_TGT }}">'
                                            + '<i class="fa fa-eye"></i></a>';
                                    }

                                    if (row.teamViewerLink !== "") {
                                        html += '<a href="' + row.teamViewerLink + '" title="{{ "TeamViewer to this Display"|trans }}" target="_blank">'
                                            + '<img src="{{ theme.rootUri() }}theme/default/img/remote_icons/teamviewer.png" alt="TeamViewer Icon"></a>';
                                    }

                                    if (row.webkeyLink !== "") {
                                        html += '<a href="' + row.webkeyLink + '" title="{{ "Webkey to this Display"|trans }}" target="_blank">'
                                            + '<img src="{{ theme.rootUri() }}theme/default/img/remote_icons/webkey.png" alt="Webkey Icon"></a>';
                                    }

                                    return html + "</div>";

                                } else if (type === "export") {
                                    if (row.teamViewerLink !== "") {
                                        return "TeamViewer: " + row.teamViewerLink;
                                    }
                                    if (row.webkeyLink !== "") {
                                        return "Webkey: " + row.webkeyLink;
                                    }
                                    if (row.teamViewerLink === "" && row.webkeyLink === "") {
                                        return "";
                                    }
                                } else {
                                    return "";
                                }
                            },
                            "visible": true,
                            "orderable": false
                        },
                        {"data": "createdDt", "visible": false, responsivePriority: 6},
                        {"data": "modifiedDt", "visible": false, responsivePriority: 6},
                        {
                            "data": "countFaults",
                            "name": "countFaults",
                            responsivePriority: 3,
                            "render": function (data, type, row) {
                                if (type != "display") {
                                    return data;
                                }

                                if (data > 0) {
                                    return '<span class="badge" style="background-color: red; color: white">'+(row.countFaults)+'</span>';
                                } else {
                                    return '';
                                }
                            }
                        },
                    ]
                });

                displayGridTable.on('draw', dataTableDraw);
                displayGridTable.on('draw', { form: $("#displaysGrid").closest(".XiboGrid").find(".FilterDiv form") }, dataTableCreateTagEvents);
                displayGridTable.on('processing.dt', dataTableProcessing);
                dataTableAddButtons(displayGridTable, $('#displaysGrid_wrapper').find('.dataTables_buttons'))}
        }
    </script>
{% endblock %}