{#
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2015 Spring Signage Ltd
 * (${FILE_NAME})
 */

#}
{% extends "authed.twig" %}
{% import "inline.twig" as inline %}

{% block actionMenu %}
    <ul class="nav nav-pills pull-right">
        <li class="btn btn-success btn-xs"><a class="btns" id="refreshGrid" title="{% trans "Refresh the Table" %}" href="#"><i class="fa fa-refresh" aria-hidden="true"></i> {% trans "Refresh" %}</a></li>
    </ul>
{% endblock %}

{% block pageContent %}
    <div class="widget">
        <div class="widget-title">{% trans "Displays" %}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-grid-name="displayView">
                <div class="XiboFilter well">
                    <div class="FilterDiv" id="Filter">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="active"><a href="#filter-general" role="tab" data-toggle="tab">{% trans "General" %}</a></li>
                            <li><a href="#filter-advanced" role="tab" data-toggle="tab">{% trans "Advanced" %}</a></li>
                        </ul>
                        <form class="form-inline">
                            <div class="tab-content">
                                <div class="tab-pane active" id="filter-general">
                                    {% set title %}{% trans "Name" %}{% endset %}
                                    {{ inline.input("display", title) }}

                                    {% set title %}{% trans "Status" %}{% endset %}
                                    {% set check %}{% trans "Up to date" %}{% endset %}
                                    {% set cloud %}{% trans "Out of date" %}{% endset %}
                                    {% set cross %}{% trans "Downloading" %}{% endset %}
                                    {% set options = [
                                        { optionid: "", option: "" },
                                        { optionid: "1", option: check},
                                        { optionid: "3", option: cloud},
                                        { optionid: "2", option: cross}
                                    ] %}
                                    {{ inline.dropdown("mediaInventoryStatus", "single", title, "", options, "optionid", "option") }}

                                    {% set title %}{% trans "Logged In?" %}{% endset %}
                                    {% set yesOption %}{% trans "Yes" %}{% endset %}
                                    {% set noOption %}{% trans "No" %}{% endset %}
                                    {% set options = [
                                        { optionid: "", option: "" },
                                        { optionid: "1", option: yesOption},
                                        { optionid: "0", option: noOption}
                                    ] %}
                                    {{ inline.dropdown("loggedIn", "single", title, "", options, "optionid", "option") }}

                                    {% set title %}{% trans "Authorised?" %}{% endset %}
                                    {% set yesOption %}{% trans "Yes" %}{% endset %}
                                    {% set noOption %}{% trans "No" %}{% endset %}
                                    {% set options = [
                                        { optionid: "", option: "" },
                                        { optionid: "1", option: yesOption },
                                        { optionid: "0", option: noOption},
                                    ] %}
                                    {{ inline.dropdown("authorised", "single", title, "", options, "optionid", "option") }}

                                    {% set title %}{% trans "Tags" %}{% endset %}
                                    {% set helpText %}{% trans "A comma separated list of tags to filter by. Enter --no-tag to see items without tags." %}{% endset %}
                                    {{ inline.inputWithTags("tags", title, null, helpText) }}

                                    {% set title %}{% trans "Display Group" %}{% endset %}
                                    {{ inline.dropdown("displayGroupId", "single", title, "", [{displayGroupId:null, displayGroup:""}]|merge(displayGroups), "displayGroupId", "displayGroup") }}

                                    {% set title %}{% trans "Display Profile" %}{% endset %}
                                    {{ inline.dropdown("displayProfileId", "single", title, "", [{displayProfileId:null, name:""}]|merge(displayProfiles), "displayProfileId", "name") }}
                                </div>

                                <div class="tab-pane" id="filter-advanced">
                                    {% set title %}{% trans "Last Accessed" %}{% endset %}
                                    <div class="form-group">
                                        <label class="control-label" for="lastAccessed">{{ title }}</label>
                                        <div class="input-group date" style="display:table;">
                                            <input type="hidden" name="lastAccessed" id="lastAccessed" />
                                            <input class="form-control datePicker dateControl" name="lastAccessedLink"
                                                   type="text" id="lastAccessedLink" data-link-field="lastAccessed"
                                                   data-link-format="yyyy-mm-dd hh:ii:ss" readonly />
                                            <span class="input-group-addon" id="lastAccessedControlCancel">
                                                <span class="fa fa-times-circle"></span>
                                            </span>
                                        </div>
                                    </div>

                                    {% set title %}{% trans "Client Type" %}{% endset %}
                                    {% set android %}{% trans "Android" %}{% endset %}
                                    {% set linux %}{% trans "Linux" %}{% endset %}
                                    {% set sssp %}{% trans "Tizen" %}{% endset %}
                                    {% set webos %}{% trans "webOS" %}{% endset %}
                                    {% set windows %}{% trans "Windows" %}{% endset %}
                                    {% set options = [
                                        { optionid: "", option: "" },
                                        { optionid: "android", option: android},
                                        { optionid: "linux", option: linux},
                                        { optionid: "sssp", option: sssp},
                                        { optionid: "lg", option: webos},
                                        { optionid: "windows", option: windows}
                                    ] %}
                                    {{ inline.dropdown("clientType", "single", title, "", options, "optionid", "option") }}

                                    {% set title %}{% trans "Client Code" %}{% endset %}
                                    {{ inline.input("clientCode", title) }}

                                    {% set title %}{% trans "Mac Address" %}{% endset %}
                                    {{ inline.input("macAddress", title) }}

                                    {% set title %}{% trans "IP Address" %}{% endset %}
                                    {{ inline.input("clientAddress", title) }}
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="XiboData">
                    <table id="displays" class="table table-striped">
                        <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 "Tags" %}</th>
                                <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 "Screen shot?" %}</th>
                                <th>{% trans "Thumbnail" %}</th>
                                <th>{% trans "Last Command" %}</th>
                                <th>{% trans "XMR Registered" %}</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>

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

{% block javaScript %}
    <script type="text/javascript">
        $(document).ready(function() {
            var table = $("#displays").DataTable({
                "language": dataTablesLanguage,
                serverSide: true,
                stateSave: true, stateDuration: 0,
                stateLoadCallback: function (settings, callback) {
                    var data = {};
                    $.ajax({
                        type: "GET",
                        async: false,
                        url: "{{ urlFor("user.pref") }}?preference=displayGrid",
                        dataType: 'json',
                        success: function (json) {
                            try {
                                if (json.success) {
                                    data = JSON.parse(json.data.value);
                                }
                            } catch (e) {
                                // Do nothing
                            }
                        }
                    });
                    return data;
                },
                stateSaveCallback: function (settings, data) {
                    $.ajax({
                        type: "POST",
                        url: "{{ urlFor("user.pref") }}",
                        data: {
                            preference: [{
                                option: "displayGrid",
                                value: JSON.stringify(data)
                            }]
                        }
                    });
                },
                filter: false,
                searchDelay: 3000,
                order: [[1, "asc"]],
                ajax: {
                    "url": "{{ urlFor("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, $("#displays").closest(".XiboGrid").find(".FilterDiv form").serializeObject());

                        return data;
                    }
                },
                createdRow: function (row, data, index) {
                    if (data.mediaInventoryStatus === 1) {
                        $(row).addClass('success');
                    } else if (data.mediaInventoryStatus === 1) {
                        $(row).addClass('danger');
                    } else {
                        $(row).addClass('warning');
                    }
                },
                "columns": [
                    {"data": "displayId"},
                    {
                        "name": "display",
                        "data": function (data, type) {
                            if (type != "display")
                                return data.display;

                            if ("{{ settings.SHOW_DISPLAY_AS_VNCLINK }}" != "" && data.clientAddress != null && data.clientAddress != "") {
                                var link = "{{ settings.SHOW_DISPLAY_AS_VNCLINK }}".replace('%s', data.clientAddress);
                                return '<a href="' + link + '" title="{% trans "VNC to this Display" %}" target="{{ settings.SHOW_DISPLAY_AS_VNC_TGT }}">' + data.display + '</a>';
                            }
                            else {
                                return data.display;
                            }
                        }
                    },
                    {
                        "data": "mediaInventoryStatus",
                        "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},
                    {"data": "currentLayout", "visible": false, "sortable": false},
                    {
                        "data": "storageAvailableSpace",
                        "visible": false,
                        "render": function (data, type, row) {
                            if (type != "display")
                                return data;

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

                            return row.storageTotalSpaceFormatted;
                        }
                    },
                    {"data": "storagePercentage", "visible": false, "sortable": false},
                    {"data": "description", "visible": false},
                    {
                        "name": "tags",
                        "sortable": false,
                        "visible": false,
                        "data": dataTableCreateTags
                    },
                    {"data": "defaultLayout", "visible": false},
                    {"data": "incSchedule", "render": dataTableTickCrossColumn, "visible": false},
                    {"data": "emailAlert", "render": dataTableTickCrossColumn, "visible": false},
                    {"data": "loggedIn", "render": dataTableTickCrossColumn},
                    {"data": "lastAccessed", "render": dataTableDateFromUnix},
                    {
                        "name": "displayProfileId",
                        "data": function (data, type) {
                            return data.displayProfile;
                        },
                        "visible": false
                    },
                    {
                        "name": "clientSort",
                        "data": function (data) {
                            return data.clientType + ' ' + data.clientVersion + '-' + data.clientCode;
                        },
                        "visible": false
                    },
                    {"data": "deviceName", "visible": false},
                    {"data": "clientAddress", "visible": false},
                    {"data": "macAddress"},
                    {"data": "timeZone", "visible": false},
                    {"data": "screenShotRequested", "render": dataTableTickCrossColumn, "visible": false, "name": "screenShotRequested"},
                    {
                        "name": "thumbnail",
                        "orderable": false,
                        "data": function (data, type) {
                            if (type != "display")
                                return data.thumbnail;

                            if (data.thumbnail != "") {
                                return '<a data-toggle="lightbox" data-type="image" href="' + data.thumbnail + '"><img class="display-screenshot" src="' + data.thumbnail + '" /></a>';
                            }
                            else {
                                return "";
                            }
                        },
                        "visible": false
                    },
                    {
                        "data": "lastCommandSuccess",
                        "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",
                        "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
                    },
                    {
                        "orderable": false,
                        "data": dataTableButtonsColumn
                    }
                ]
            });

            table.on('draw', dataTableDraw);
            table.on('draw', { form: $("#displays").closest(".XiboGrid").find(".FilterDiv form") }, dataTableCreateTagEvents);
            table.on('processing.dt', dataTableProcessing);
            dataTableAddButtons(table, $('#displays_wrapper').find('.col-sm-6').eq(1));

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

            $("#lastAccessedControlCancel").on('click', function() {
                // Clear the date picker
                var $lastAccessed = $("#lastAccessed");
                $lastAccessed.val("");
                $("#lastAccessedLink").val("");

                table.ajax.reload();

                // Reset local storage
                localStorage.setItem("displayView", JSON.stringify($lastAccessed.closest("form").serializeArray()));
            });
        });

        function displayRequestScreenshotFormSubmit() {
            $("#displayRequestScreenshotForm").submit();
            XiboDialogClose();
            var table = $('#displays').DataTable();

            if (!table.column(["thumbnail:name"]).visible()) {
                table.columns(["screenShotRequested:name", "thumbnail:name"]).visible(true);
            }
        }

        function setDefaultMultiSelectFormOpen(dialog) {
            console.log('Multi-select form opened for default layout');

            // Inject a list of layouts into the form, in a drop down.
            var $select = $('<select name="layoutId" class="form-control" data-search-url="{{ urlFor("layout.search") }}" data-search-term="layout" data-id-property="layoutId" data-text-property="layout">');
            $select.on('change', function() {
                console.log('Setting commit data to ' + $(this).val());
                dialog.data().commitData = {layoutId: $(this).val()};
            });

            // Add the list to the body.
            $(dialog).find('.modal-body').append($select);

            makePagedSelect($select, dialog);
        }
    </script>
{% endblock %}