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

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

{% block actionMenu %}
    {% if currentUser.featureEnabled("layout.add") %}
    <div class="widget-action-menu pull-right">
        <button class="btn btn-success XiboFormButton" title="{% trans "Add a new Layout and jump to the layout designer." %}" href="{{ url_for("layout.add.form") }}"><i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add Layout" %}</button>
        <button class="btn btn-info" id="layoutUploadForm" title="{% trans "Import a Layout from a ZIP file." %}" href="#"> <i class="fa fa-cloud-download" aria-hidden="true"></i> {% trans "Import" %}</button>
    </div>
    {% endif %}
{% endblock %}

{% block pageContent %}
    <div class="widget">
        <div class="widget-title">{% trans "Layouts" %}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}" data-grid-type="layout" data-grid-name="layoutView">
                <div class="XiboFilter card mb-3 bg-light">
                    <div class="FilterDiv card-body" id="Filter">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="nav-item"><a class="nav-link active" href="#general-filter" role="tab" data-toggle="tab" aria-selected="true"><span>{% trans "General" %}</span></a></li>
                            <li class="nav-item"><a class="nav-link" href="#advanced-filter" role="tab" data-toggle="tab" aria-selected="false"><span>{% trans "Advanced" %}</span></a></li>
                        </ul>
                        <form class="form-inline d-block">
                            <div class="tab-content">
                                <div class="tab-pane active" id="general-filter" role="tabpanel">
                                    {% set title %}{% trans "ID" %}{% endset %}
                                    {{ inline.number("layoutId", title) }}

                                    <div class="form-group mr-1 mb-1">
                                        <label class="control-label mr-1" title="" for="layout" accesskey="">{% trans "Name" %}</label>
                                        <div class="input-group">
                                            <input class="form-control" name="layout" type="text" id="layout" value="">
                                            <div class="input-group-append input-group-addon">
                                                <div class="input-group-text">
                                                    <input title="{% trans "Use Regex?" %}" type="checkbox" id="useRegexForName" name="useRegexForName">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {% if currentUser.featureEnabled("tag.tagging") %}
                                        {% set title %}{% trans "Tags" %}{% endset %}
                                        {% set exactTagTitle %}{% trans "Exact match?" %}{% endset %}
                                        {% set helpText %}{% trans "A comma separated list of tags to filter by. Enter a Tag value preceded with | to filter by Tag values. Enter --no-tag to see items without tags." %}{% endset %}
                                        {{ inline.inputWithTags("tags", title, null, helpText, null, null, null, "exactTags", exactTagTitle) }}
                                    {% 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 %}
                                    {{ inline.dropdown("userId", "single", title, "", [{userId:null, userName:""}]|merge(users), "userId", "userName", helpText, "selectPicker", "", "", "", attributes) }}

                                    {% set title %}{% trans "Owner User Group" %}{% endset %}
                                    {% set helpText %}{% trans "Show items owned by users in the selected User Group." %}{% endset %}
                                    {{ inline.dropdown("ownerUserGroupId", "single", title, "", [{groupId:null, group:""}]|merge(groups), "groupId", "group", helpText, "selectPicker", "", "", "", attributes) }}

                                    {% if currentUser.featureEnabled("displaygroup.view") %}
                                        {% set title %}{% trans "Display Group" %}{% endset %}
                                        {% set helpText %}{% trans "Show Layouts active on the selected Display / Display Group" %}{% endset %}
                                        {{ inline.dropdown("activeDisplayGroupId", "single", title, "", [{displayGroupId:null, displayGroup:""}]|merge(displayGroups), "displayGroupId", "displayGroup", helpText, "selectPicker", "", "", "", attributes) }}
                                    {% endif %}

                                    {{ inline.hidden("folderId") }}
                                </div>
                                <div class="tab-pane" id="advanced-filter" role="tabpanel">

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

                                    {% set title %}{% trans "Show" %}{% endset %}
                                    {% set option1 = "All"|trans %}
                                    {% set option2 = "Only Used"|trans %}
                                    {% set option3 = "Only Unused"|trans %}
                                    {% set values = [{id: 1, value: option1}, {id: 2, value: option2}, {id: 3, value: option3}] %}
                                    {{ inline.dropdown("layoutStatusId", "single", title, 1, values, "id", "value") }}

                                    {% set title %}{% trans "Description" %}{% endset %}
                                    {% set option1 = "All"|trans %}
                                    {% set option2 = "1st line"|trans %}
                                    {% set option3 = "Widget List"|trans %}
                                    {% set values = [{id: 1, value: option1}, {id: 2, value: option2}, {id: 3, value: option3}] %}
                                    {{ inline.dropdown("showDescriptionId", "single", title, 2, values, "id", "value") }}

                                    {% if currentUser.featureEnabled("library.view") %}
                                        {% set title %}{% trans "Media" %}{% endset %}
                                        {{ inline.input("mediaLike", title) }}
                                    {% endif %}
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-1 form-group" style="padding: 0">
                        <button type="button" id="folder-tree-select-folder-button" class="btn btn-outline-secondary btn-sm" title="{% trans "Open / Close Folder Search options" %}"><i class="fas fa-bars fa-1x"></i></button>
                    </div>
                    <div class="form-group col-sm-11" style="padding: 0">
                        <div id="breadcrumbs" style="margin-top: 5px;"></div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-2 p-3 bg-light" id="grid-folder-filter">
                        <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 "Global Search" %}</label>
                        </div>
                        <div id="container-folder-tree"></div>
                    </div>
                    <div id="datatable-container" class="card col-sm-10 pt-4 px-2">
                        <div class="XiboData">
                            <table id="layouts" class="table table-striped responsive nowrap" data-content-type="layout" data-content-id-name="layoutId" data-state-preference-name="layoutGrid" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th>{% trans "ID" %}</th>
                                        <th>{% trans "Name" %}</th>
                                        <th>{% trans "Status" %}</th>
                                        <th>{% trans "Description" %}</th>
                                        <th>{% trans "Duration" %}</th>
                                        {% if currentUser.featureEnabled("tag.tagging") %}<th>{% trans "Tags" %}</th>{% endif %}
                                        <th>{% trans "Thumbnail" %}</th>
                                        <th>{% trans "Owner" %}</th>
                                        <th>{% trans "Sharing" %}</th>
                                        <th>{% trans "Valid?" %}</th>
                                        <th>{% trans "Stats?" %}</th>
                                        <th>{% trans "Created" %}</th>
                                        <th>{% trans "Modified" %}</th>
                                        <th>{% trans "Code" %}</th>
                                        <th class="rowMenu"></th>
                                    </tr>
                                </thead>
                                <tbody>

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

{% block javaScript %}
    <script type="text/javascript">
        var table;
        $(document).ready(function() {
            {% if not currentUser.featureEnabled("folder.view") %}
            disableFolders();
            {% endif %}

            table = $("#layouts").DataTable({
                "language": dataTablesLanguage,
                "lengthMenu": [10, 25, 50, 100, 250, 500],
                serverSide: true,
                stateSave: true,
                stateDuration: 0,
                responsive: true,
                stateLoadCallback: dataTableStateLoadCallback,
                stateSaveCallback: dataTableStateSaveCallback,
                filter: false,
                searchDelay: 3000,
                dataType: 'json',
                "order": [[1, "asc"]],
                ajax: {
                    url: "{{ url_for("layout.search") }}",
                    "data": function (d) {
                        $.extend(d, $("#layouts").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                    }
                },
                "columns": [
                    {"data": "layoutId", responsivePriority: 2},
                    {
                        "data": "layout",
                        responsivePriority: 2,
                        "render": dataTableSpacingPreformatted
                    },
                    {
                        "name": "publishedStatus",
                        responsivePriority: 2,
                        "data": function (data, type) {
                            if (data.publishedDate != null) {
                                var now = moment();
                                var published = moment(data.publishedDate);
                                var differenceMinutes = published.diff(now, 'minutes');
                                var momentDifference = moment(now).to(published);

                                if (differenceMinutes < -5) {
                                    return data.publishedStatus.concat(" - ", data.publishedStatusFailed);
                                } else {
                                    return data.publishedStatus.concat(" - ", data.publishedStatusFuture.replace('%s', momentDifference));
                                }
                            } else {
                                return data.publishedStatus;
                            }

                        }
                    },
                    {
                        "name": "description",
                        "data": null,
                        responsivePriority: 5,
                        "render": {"_": "description", "display": "descriptionFormatted", "sort": "description"}
                    },
                    {
                        "name": "duration",
                        responsivePriority: 3,
                        "data": function (data, type) {
                            if (type != "display")
                                return data.duration;

                            return dataTableTimeFromSeconds(data.duration, type);
                        }
                    },
                    {% if currentUser.featureEnabled("tag.tagging") %}{
                        "sortable": false,
                        "visible": false,
                        responsivePriority: 3,
                        "data": dataTableCreateTags
                    },{% endif %}
                    {
                        "name": "layoutId",
                        responsivePriority: 5,
                        "data": null,
                        "render": {"_": "thumbnail", "display": "thumbnail", "sort": "layoutId"}
                    },
                    {"data": "owner", responsivePriority: 4},
                    {
                        "data": "groupsWithPermissions",
                        responsivePriority: 4,
                        "render": dataTableCreatePermissions
                    },
                    {
                        "name": "status",
                        responsivePriority: 3,
                        "data": function (data, type) {
                            if (type != "display")
                                return data.status;

                            var icon = "";
                            if (data.status == 1)
                                icon = "fa-check";
                            else if (data.status == 2)
                                icon = "fa-exclamation";
                            else if (data.status == 3)
                                icon = "fa-cogs";
                            else
                                icon = "fa-times";

                            return '<span class="fa ' + icon + '" title="' + (data.statusDescription) + ((data.statusMessage == null) ? "" : " - " + (data.statusMessage)) + '"></span>';
                        }
                    },
                    {
                        "name": "enableStat",
                        responsivePriority: 4,
                        "data": function (data) {

                            var icon = "";
                            if (data.enableStat == 1)
                                icon = "fa-check";
                            else
                                icon = "fa-times";

                            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
                    },
                    {"data": "code", "visible":false, responsivePriority: 4},
                    {
                        "orderable": false,
                        responsivePriority: 1,
                        "data": dataTableButtonsColumn
                    }
                ]
            });

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

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

            // Open the upload dialog with our options.
            openUploadForm({
                url: "{{ url_for("layout.import") }}",
                title: "{% trans "Upload Layout" %}",
                multi: true,
                videoImageCovers: false,
                buttons: {
                    main: {
                        label: "{% trans "Done" %}",
                        className: "btn-primary btn-bb-main",
                        callback: function () {
                            table.ajax.reload();
                            XiboDialogClose();
                        }
                    }
                },
                templateOptions: {
                    layoutImport: true,
                    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 Layout Export ZIP Files" %}",
                        startUpload: "{% trans "Start Import" %}",
                        cancelUpload: "{% trans "Cancel Import" %}",
                        replaceExistingMediaMessage: "{% trans "Replace Existing Media?" %}",
                        importTagsMessage: "{% trans "Import Tags?" %}",
                        useExistingDataSetsMessage: "{% trans "Use existing DataSets matched by name?" %}",
                        dataSetDataMessage: "{% trans "Import DataSet Data?" %}",
                        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: "zip"
                    },
                    currentWorkingFolderId: currentWorkingFolderId,
                    folderSelector: true
                },
                formOpenedEvent: function () {
                    // Configure the active behaviour of the checkboxes
                    $("#useExistingDataSets").on("click", function () {
                        $("#importDataSetData").prop("disabled", ($(this).is(":checked")));
                    });
                },
                uploadDoneEvent: function (data) {
                    XiboDialogClose();
                    table.ajax.reload();
                }
            });
        });

        function layoutAddFormOpen() {
            if ($('#folder-tree-form-modal').length === 0) {
                // compile tree folder modal and append it to Form
                var folderTreeModal = Handlebars.compile($('#folder-tree-template').html());
                var treeConfig = {"container": "container-folder-form-tree", "modal": "folder-tree-form-modal"};
                $("body").append(folderTreeModal(treeConfig));

                $("#folder-tree-form-modal").on('hidden.bs.modal', function () {
                    // Fix for 2nd/overlay modal
                    $('.modal:visible').length && $(document.body).addClass('modal-open');
                    
                    $(this).data('bs.modal', null);
                });
            }

            // select current working folder if one is selected in the grid
            if ($('#container-folder-tree').jstree("get_selected", true)[0] !== undefined) {
                $('#layoutAddForm' + ' #folderId').val($('#container-folder-tree').jstree("get_selected", true)[0].id);
            }

            initJsTreeAjax($('#folder-tree-form-modal').find('#container-folder-form-tree'), 'layoutAddForm', true, 600);

            $("#layoutAddForm").submit(function(e) {
                e.preventDefault();
                var form = $(this);

                var url = $(this).data().redirect;

                $.ajax({
                    type: $(this).attr("method"),
                    url: $(this).attr("action"),
                    data: $(this).serialize(),
                    cache: false,
                    dataType:"json",
                    success: function(xhr, textStatus, error) {

                        XiboSubmitResponse(xhr, form);

                        if (xhr.success) {
                            // Reload the designer
                            XiboRedirect(url.replace(":id", xhr.id));
                        }
                    }
                });
            });
        }

        function layoutExportFormSubmit() {
            var $form = $("#layoutExportForm");
            window.location = $form.attr("action") + "?" + $form.serialize();

            setTimeout(function() {
                XiboDialogClose();
            }, 1000);
        }

        function assignLayoutToCampaignFormSubmit() {
            var form = $("#layoutAssignCampaignForm");

            var url = form.prop("action").replace(":id", form.find("#campaignId").val());

            $.ajax({
                type: form.attr("method"),
                url: url,
                data: {layoutId: form.data().layoutId},
                cache: false,
                dataType:"json",
                success: XiboSubmitResponse
            });
        }

        function setEnableStatMultiSelectFormOpen(dialog) {
            var $input = $('<input type=checkbox id="enableStat" name="enableStat"> {% trans %} Enable Stats Collection? {% endtrans %} </input>');
            var $helpText = $('<span class="help-block">Check to enable the collection of Proof of Play statistics for the selected items. </span>');

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

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

    </script>
{% endblock %}