{#
/**
 * Copyright (C) 2022 Xibo Signage Ltd
 *
 * Xibo - Digital Signage - http://www.xibo.org.uk
 *
 * This file is part of Xibo.
 *
 * Xibo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Xibo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */
#}
{% extends "authed.twig" %}
{% import "inline.twig" as inline %}

{% block title %}{{ "Library"|trans }} | {% endblock %}

{% block actionMenu %}
    <div class="widget-action-menu pull-right">
        {% if currentUser.featureEnabledCount(["library.add", "library.modify"]) > 0 or settings.SETTING_LIBRARY_TIDY_ENABLED == 1 %}
            {% if currentUser.featureEnabled("library.add") %}
                <button class="btn btn-success" href="#" id="libraryUploadForm" title="{% trans "Add a new media item to the library" %}"><i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add Media" %}</button>
                <button class="btn btn-success XiboFormButton" title="{% trans "Add a new media item to the library via external URL" %}" href="{{ url_for("library.uploadUrl.form") }}"> <i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add media (URL)" %}</button>
            {% endif %}
            {% if settings.SETTING_LIBRARY_TIDY_ENABLED == 1 and currentUser.featureEnabled("library.modify") %}
                <button class="btn btn-danger XiboFormButton" title="{% trans "Run through the library and remove unused and unnecessary files" %}" href="{{ url_for("library.tidy.form") }}"> <i class="fa fa-trash" aria-hidden="true"></i> {% trans "Tidy Library" %}</button>
            {% endif %}
        {% endif %}
        <button class="btn btn-primary" id="refreshGrid" title="{% trans "Refresh the Table" %}" href="#"><i class="fa fa-refresh" aria-hidden="true"></i></button>
    </div>
{% endblock %}


{% block pageContent %}
    <div class="widget">
        <div class="widget-title">{% trans "Library" %}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-grid-name="libraryView">
                <div class="XiboFilter card mb-3 bg-light">
                    <div class="FilterDiv card-body" id="Filter">
                        <form class="form-inline">
                            {% set title %}{% trans "ID" %}{% endset %}
                            {{ inline.number("mediaId", title) }}

                            {% set title %}{% trans "Name" %}{% endset %}
                            {{ inline.inputNameGrid('media', title) }}

                            {% if currentUser.featureEnabled("tag.tagging") %}
                                {% set title %}{% trans "Tags" %}{% endset %}
                                {% set exactTagTitle %}{% trans "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", exactTagTitle, logicalOperatorTitle) }}
                            {% endif %}

                            {% set attributes = [
                                { name: "data-allow-clear", value: "true" },
                                { name: "data-placeholder--id", value: null },
                                { name: "data-placeholder--value", value: "" }
                            ] %}

                            {% set title %}{% trans "Owner" %}{% endset %}
                            {% set helpText %}{% trans "Show items owned by the selected User." %}{% 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("user.search") },
                                { name: "data-search-term", value: "userName" },
                                { name: "data-search-term-tags", value: "tags" },
                                { name: "data-id-property", value: "userId" },
                                { name: "data-text-property", value: "userName" },
                                { name: "data-initial-key", value: "userId" },
                            ] %}
                            {{ inline.dropdown("ownerId", "single", title, "", null, "userId", "userName", helpText, "pagedSelect", "", "", "", attributes) }}

                            {% set title %}{% trans "Owner User Group" %}{% endset %}
                            {% set helpText %}{% trans "Show items owned by users in the selected User 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("group.search") },
                                { name: "data-search-term", value: "group" },
                                { name: "data-id-property", value: "groupId" },
                                { name: "data-text-property", value: "group" },
                                { name: "data-initial-key", value: "userGroupId" },
                            ] %}
                            {{ inline.dropdown("ownerUserGroupId", "single", title, "", null, "groupId", "group", helpText, "pagedSelect", "", "", "", attributes) }}

                            {% set title %}{% trans "Type" %}{% endset %}
                            {{ inline.dropdown("type", "single", title, "", [{"type": none, "name": ""}]|merge(modules), "type", "name") }}

                            {% set title %}{% trans "Retired" %}{% endset %}
                            {% set values = [{id: 0, value: "No"}, {id: 1, value: "Yes"}] %}
                            {{ inline.dropdown("retired", "single", title, 0, values, "id", "value") }}

                            {{ inline.hidden("folderId") }}

                            {% set title %}{% trans "Layout ID" %}{% endset %}
                            {{ inline.number("layoutId", title, layoutId) }}

                            {% set title %}{% trans "Orientation" %}{% endset %}
                            {% set option1 = "All"|trans %}
                            {% set option2 = "Landscape"|trans %}
                            {% set option3 = "Portrait"|trans %}
                            {% set values = [{id: '', value: option1}, {id: 'landscape', value: option2}, {id: 'portrait', value: option3}] %}
                            {{ inline.dropdown("orientation", "single", title, '', values, "id", "value") }}
                        </form>
                    </div>
                </div>
                <div class="grid-with-folders-container">
                    <div class="grid-folder-tree-container p-3" id="grid-folder-filter">
                        <input id="jstree-search" class="form-control" type="text" placeholder="{% trans "Search" %}">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="folder-tree-clear-selection-button">
                            <label class="form-check-label" for="folder-tree-clear-selection-button" title="{% trans "Search in all folders" %}">{% trans "All Folders" %}</label>
                        </div>
                        <div class="folder-search-no-results d-none">
                            <p>{% trans 'No Folders matching the search term' %}</p>
                        </div>
                        <div id="container-folder-tree"></div>
                    </div>
                    <div class="folder-controller d-none">
                        <button type="button" id="folder-tree-select-folder-button" class="btn btn-outline-secondary" title="{% trans "Open / Close Folder Search options" %}"><i class="fas fa-folder fa-1x"></i></button>
                        <div id="breadcrumbs" class="mt-2 pl-2"></div>
                    </div>
                    <div id="datatable-container">
                        <div class="XiboData card py-3">
                            <table id="libraryItems" class="table table-striped responsive nowrap" data-content-type="media" data-content-id-name="mediaId" data-state-preference-name="libraryGrid" style="width: 100%;">
                                <thead>
                                <tr>
                                    <th>{% trans "ID" %}</th>
                                    <th>{% trans "Name" %}</th>
                                    <th>{% trans "Type" %}</th>
                                    {% if currentUser.featureEnabled("tag.tagging") %}<th>{% trans "Tag" %}</th>{% endif %}
                                    <th>{% trans "Thumbnail" %}</th>
                                    <th>{% trans "Duration" %}</th>
                                    <th>{% trans "Duration (seconds)" %}</th>
                                    <th>{% trans "Size" %}</th>
                                    <th>{% trans "Size (bytes)" %}</th>
                                    <th>{% trans "Resolution" %}</th>
                                    <th>{% trans "Owner" %}</th>
                                    <th>{% trans "Sharing" %}</th>
                                    <th>{% trans "Revised" %}</th>
                                    <th>{% trans "Released" %}</th>
                                    <th>{% trans "File Name" %}</th>
                                    <th>{% trans "Stats?" %}</th>
                                    <th>{% trans "Created" %}</th>
                                    <th>{% trans "Modified" %}</th>
                                    <th>{% trans "Expires" %}</th>
                                    <th class="rowMenu"></th>
                                </tr>
                                </thead>
                                <tbody>

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

{% block javaScript %}
    <script type="text/javascript" nonce="{{ cspNonce }}">
        var table;
        $(document).ready(function() {

            {% if not currentUser.featureEnabled("folder.view") %}
            disableFolders();
            {% endif %}

            table = $("#libraryItems").DataTable({
                "language": dataTablesLanguage,
                dom: dataTablesTemplate,
                serverSide: true,
                stateSave: true,
                responsive: true,
                stateDuration: 0,
                stateLoadCallback: dataTableStateLoadCallback,
                stateSaveCallback: dataTableStateSaveCallback,
                filter: false,
                searchDelay: 3000,
                "order": [[1, "asc"]],
                ajax: {
                    "url": "{{ url_for("library.search") }}",
                    "data": function (d) {
                        $.extend(d, $("#libraryItems").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                    }
                },
                "columns": [
                    {"data": "mediaId", responsivePriority: 2},
                    {"data": "name", "render": dataTableSpacingPreformatted, responsivePriority: 3 },
                    {"data": "mediaType", responsivePriority: 2},
                    {% if currentUser.featureEnabled("tag.tagging") %}{
                        "sortable": false,
                        responsivePriority: 2,
                        "visible": false,
                        "data": dataTableCreateTags
                    },{% endif %}
                    {
                        responsivePriority: 5,
                        data: 'thumbnail',
                        render: function(data, type, row) {
                            if (type !== 'display') {
                                return row.mediaId;
                            }
                            if (data) {
                                return '<a class="img-replace" data-toggle="lightbox" data-type="image" href="' + data + '">' +
                                    '<img class="img-fluid" src="' + data.replace('download', 'thumbnail') + '" alt="{{ "Thumbnail"|trans }}" />' +
                                    '</a>';
                            }
                            return '';
                        },
                        sortable: false
                    },
                    {
                        "name": "duration",
                        responsivePriority: 3,
                        "data": function (data, type) {
                            if (type != "display")
                                return data.duration;

                            return dataTableTimeFromSeconds(data.duration, type);
                        }
                    },
                    {"data": "duration", "visible": false, responsivePriority: 10},
                    {
                        "name": "fileSize",
                        responsivePriority: 3,
                        "data": null,
                        "render": {"_": "fileSize", "display": "fileSizeFormatted", "sort": "fileSize"}
                    },
                    {"data": "fileSize", "visible": false, responsivePriority: 10},
                    {
                        name: 'width',
                        data: function(data, type, row, meta) {
                            if (type !== 'display' || data.width === 0 || data.height === 0) {
                                return '';
                            }

                            return data.width + 'x' + data.height;
                        },
                        visible: false,
                        responsivePriority: 10
                    },
                    {"data": "owner", responsivePriority: 5},
                    {
                        "data": "groupsWithPermissions",
                        responsivePriority: 5,
                        "render": dataTableCreatePermissions
                    },
                    {"data": "revised", "render": dataTableTickCrossColumn, "visible": false, responsivePriority: 6},
                    {
                        "name": "released",
                        responsivePriority: 6,
                        "data": function (data, type) {
                            if (type != "display")
                                return data.released;

                            var icon = "";
                            if (data.released == 1)
                                icon = "fa-check";
                            else if (data.released == 0)
                                icon = "fa-cogs";
                            else if (data.released == 2)
                                icon = "fa-times";


                            return '<span class="fa ' + icon + '" title="' + (data.releasedDescription) + '"></span>';
                        },
                        "visible": false
                    },
                    {"data": "fileName", responsivePriority: 500},
                    {
                        "name": "enableStat",
                        responsivePriority: 6,
                        "data": function (data) {

                            var icon = "";
                            if (data.enableStat == 'On')
                                icon = "fa-check";
                            else if (data.enableStat == 'Off')
                                icon = "fa-times";
                            else
                                icon = "fa-level-down";

                            return '<span class="fa ' + icon + '" title="' + (data.enableStatDescription) + '"></span>';
                        }
                    },
                    {
                        "data": "createdDt",
                        responsivePriority: 6,
                        "render": dataTableDateFromIso,
                        "visible": false
                    },
                    {
                        "data": "modifiedDt",
                        responsivePriority: 6,
                        "render": dataTableDateFromIso,
                        "visible": false
                    },
                    {
                        "name": "expires",
                        responsivePriority: 6,
                        "data": function (data, type) {
                            if (data.expires != null && data.expires != 0) {
                                var now = moment();
                                var expiresIn = moment.unix(data.expires);
                                var differenceMinutes = expiresIn.diff(now, 'minutes');
                                var momentDifference = moment(now).to(expiresIn);

                                if (differenceMinutes < -10 ) {
                                    return data.mediaExpiryFailed;
                                } else {
                                    return data.mediaExpiresIn.replace('%s', momentDifference);
                                }
                            } else {
                                return data.mediaNoExpiryDate;
                            }

                        }
                    },
                    {
                        "orderable": false,
                        responsivePriority: 1,
                        "data": dataTableButtonsColumn
                    }
                ]
            });

            table.on('draw', dataTableDraw);
            table.on('draw', { form: $("#libraryItems").closest(".XiboGrid").find(".FilterDiv form") } ,dataTableCreateTagEvents);
            table.on('processing.dt', dataTableProcessing);
            dataTableAddButtons(table, $('#libraryItems_wrapper').find('.dataTables_buttons'));

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

        $("#libraryUploadForm").click(function(e) {
            e.preventDefault();
            var currentWorkingFolderId = $('#folderId').val();

            openUploadForm({
                url: "{{ url_for("library.add") }}",
                title: "{% trans "Add Media" %}",
                initialisedBy: "library-upload",
                buttons: {
                    main: {
                        label: "{% trans "Done" %}",
                        className: "btn-primary btn-bb-main",
                        callback: function () {
                            table.ajax.reload();
                            XiboDialogClose();
                        }
                    }
                },
                templateOptions: {
                    trans: {
                        addFiles: "{% trans "Add files" %}",
                        startUpload: "{% trans "Start upload" %}",
                        cancelUpload: "{% trans "Cancel upload" %}",
                        selectFolder: "{% trans "Select Folder" %}",
                        selectFolderTitle: "{% trans "Change Current Folder location" %}",
                        selectedFolder: "{% trans "Current Folder" %}:",
                        selectedFolderTitle: "{% trans "Upload files to this Folder" %}",
                    },
                    upload: {
                        maxSize: {{ libraryUpload.maxSize }},
                        maxSizeMessage: "{{ libraryUpload.maxSizeMessage }}",
                        validExt: "{{ validExt }}"
                    },
                    updateInAllChecked: {% if settings.LIBRARY_MEDIA_UPDATEINALL_CHECKB == 1 %}true{% else %}false{% endif %},
                    deleteOldRevisionsChecked: {% if settings.LIBRARY_MEDIA_DELETEOLDVER_CHECKB == 1 %}true{% else %}false{% endif %},
                    currentWorkingFolderId: currentWorkingFolderId,
                    folderSelector: true
                }
            });
        });

        /**
         * Media Edit form
         */
        function mediaEditFormOpen(dialog) {
            // Create a new button
            var footer = dialog.find(".modal-footer");
            var mediaId = dialog.find("#mediaEditForm").data().mediaId;
            var validExtensions = dialog.find("#mediaEditForm").data().validExtensions;
            var folderId = dialog.find("#mediaEditForm").data().folderId;

            // Append
            var replaceButton = $('<button class="btn btn-warning">{% trans "Replace" %}</button>');
            replaceButton.click(function(e) {
                e.preventDefault();

                // Open the upload dialog with our options.
                openUploadForm({
                    url: "{{ url_for("library.add") }}",
                    title: "{% trans "Upload media" %}",
                    buttons: {
                        main: {
                            label: "{% trans "Done" %}",
                            className: "btn-primary btn-bb-main",
                            callback: function () {
                                table.ajax.reload();
                                XiboDialogClose();
                            }
                        }
                    },
                    templateOptions: {
                        multi: false,
                        oldMediaId: mediaId,
                        oldFolderId: folderId,
                        updateInAllChecked: {% if settings.LIBRARY_MEDIA_UPDATEINALL_CHECKB == 1 %}true{% else %}false{% endif %},
                        deleteOldRevisionsChecked: {% if settings.LIBRARY_MEDIA_DELETEOLDVER_CHECKB == 1 %}true{% else %}false{% endif %},
                        trans: {
                            addFiles: "{% trans "Add Replacement" %}",
                            startUpload: "{% trans "Start Replace" %}",
                            cancelUpload: "{% trans "Cancel Replace" %}",
                            updateInLayouts: {
                                title: "{% trans "Update this media in all layouts it is assigned to?" %}",
                                helpText: "{% trans "Note: It will only be updated in layouts you have permission to edit." %}"
                            },
                            deleteOldRevisions: {
                                title: "{% trans "Delete the old version?" %}",
                                helpText: "{% trans "Completely remove the old version of this media item if a new file is being uploaded." %}"
                            }
                        },
                        upload: {
                            maxSize: {{ libraryUpload.maxSize }},
                            maxSizeMessage: "{{ libraryUpload.maxSizeMessage }}",
                            validExt: validExtensions,
                            validExtensionsMessage: "{{ "Valid extensions are %s" }}".replace("%s", validExtensions).replace(/\|/g, ", ")
                        }
                    },
                    uploadDoneEvent: function () {
                        XiboDialogClose();
                        table.ajax.reload();
                    }
                });
            });

            footer.find(".btn-primary").before(replaceButton);
        }

        ///
        /// Library Usage Form
        ///
        function usageFormOpen(dialog) {
            // Displays tab
            var usageTable = $("#usageReportTable").DataTable({
                "language": dataTablesLanguage,
                serverSide: true,
                stateSave: true, stateDuration: 0,
                filter: false,
                searchDelay: 3000,
                responsive: true,
                "order": [[1, "asc"]],
                ajax: {
                    "url": "{{ url_for("library.usage", {id: ':id'}) }}".replace(":id", $("#usageReportTable").data().mediaId),
                    "data": function(dataDisplay) {
                        $.extend(dataDisplay, $(dialog).find("#usageReportForm").serializeObject());
                        return dataDisplay;
                    }
                },
                "columns": [
                    { "data": "displayId"},
                    { "data": "display" },
                    { "data": "description" }
                ]
            });

            usageTable.on('draw', dataTableDraw);
            usageTable.on('processing.dt', dataTableProcessing);

            // Layouts tab
            var usageTableLayouts = $("#usageReportLayoutsTable").DataTable({
                "language": dataTablesLanguage,
                serverSide: true,
                stateSave: true, stateDuration: 0,
                filter: false,
                searchDelay: 3000,
                responsive: true,
                "order": [[1, "asc"]],
                ajax: {
                    "url": "{{ url_for("library.usage.layouts", {id: ':id'}) }}".replace(":id", $("#usageReportLayoutsTable").data().mediaId)
                },
                "columns": [
                    { "data": "layoutId"},
                    { "data": "layout" },
                    { "data": "description" },
                    {
                        "orderable": false,
                        "data": dataTableButtonsColumn
                    }
                ]
            });

            usageTableLayouts.on('draw', dataTableDraw);
            usageTableLayouts.on('processing.dt', dataTableProcessing);
        }

        function setDefaultMultiSelectFormOpen(dialog) {
            {% set message = 'Force delete from any existing layouts, assignments, etc' %}
            {% set message2 = 'Notify each Display that has this Media in its local storage to remove it immediately?' %}

            var $input = $(
                '<div class="form-group">' +
                 '<input type=checkbox id="forceDelete" name="forceDelete"> {{ message|trans|e }} </input>' +
                '</div>'
            );

            var $input2 = $(
                '<div class="form-group">' +
                '<input type=checkbox id="purge" name="purge"> {{ message2|trans|e }} </input>' +
                '</div>'
            );

            $(dialog).find('.modal-body').append($input, $input2);

            $('#forceDelete, #purge').on('change', function() {
                dialog.data().commitData = {
                    forceDelete: $('#forceDelete').val(),
                    purge: $('#purge').val()
                };
            });
        }

        function setEnableStatMultiSelectFormOpen(dialog) {

            var $select = $('<select id="enableStat" name="enableStat" class="form-control">' +
                '<option value="Off">{% trans %} Off {% endtrans %}</option>' +
                '<option value="On">{% trans %} On {% endtrans %}</option>' +
                '<option value="Inherit">{% trans %} Inherit {% endtrans %}</option>' +
                '</select>');

            $select.on('change', function() {
                dialog.data().commitData = {enableStat: $(this).val()};
            }).trigger('change');

            $(dialog).find('.modal-body').append($select);
        }

    </script>
{% endblock %}