{#
 * Copyright (C) 2019 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 actionMenu %}
    <ul class="nav nav-pills pull-right">
        <li class="btn btn-success btn-xs"><a class="XiboFormButton btns" href="{{ urlFor("playlist.add.form") }}"><i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add Playlist" %}</a></li>
    </ul>
{% endblock %}

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

                                    {% set title %}{% trans "Tags" %}{% 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) }}

                                    {% set title %}{% trans "Exact match?" %}{% endset %}
                                    {{ inline.checkbox("exactTags", title) }}

                                    {% set attributes = [
                                    { name: "data-live-search", value: "true" },
                                    { name: "data-selected-text-format", value: "count > 4" }
                                    ] %}

                                    {% 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) }}

                                </div>
                                <div class="tab-pane" id="advanced-filter">

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

                                    {% set title %}{% trans "Media" %}{% endset %}
                                    {{ inline.input("mediaLike", title) }}
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="XiboData">
                    <table id="playlists" class="table table-striped">
                        <thead>
                            <tr>
                                <th>{% trans "ID" %}</th>
                                <th>{% trans "Name" %}</th>
                                <th>{% trans "Duration" %}</th>
                                <th>{% trans "Tags" %}</th>
                                <th>{% trans "Dynamic?" %}</th>
                                <th>{% trans "Owner" %}</th>
                                <th>{% trans "Permissions" %}</th>
                                <th>{% trans "Created" %}</th>
                                <th>{% trans "Modified" %}</th>
                                <th>{% trans "Stats?" %}</th>
                                <th>{% trans "Row Menu" %}</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="dummyLayout" style="display:none"></div>

    <div id="editor-container"></div>

    <div class="loading-overlay">
        <i class="fa fa-spinner fa-spin loading-icon"></i>
    </div>
    
{% endblock %}

{% block javaScript %}
    {# Add common file #}
    {% include "common.twig" %}
    
    <script src="{{ theme.rootUri() }}dist/playlistEditor.bundle.min.js"></script>
    <script type="text/javascript">

        {# Custom translations #}
        {% autoescape "js" %}
             {# Insert custom translations here #}
        {% endautoescape %}

        var table;
        $(document).ready(function() {

            // Create ourselves a little hidden layout for preview sizing, etc
            $("#dummyLayout").html('<div id="layout" data-background-color="#000000" style="background-color: #000000" designer_scale="1"><div id="region_-1" zindex="1" tip_scale="1" designer_scale="1" width="800" height="450"></div></div>');

            // Configure the DataTable
            table = $("#playlists").DataTable({
                "language": dataTablesLanguage,
                "lengthMenu": [10, 25, 50, 100, 250, 500],
                serverSide: true,
                stateSave: true,
                stateLoadCallback: function (settings, callback) {
                    var data = {};
                    $.ajax({
                        type: "GET",
                        async: false,
                        url: "{{ urlFor("user.pref") }}?preference=playlistGrid",
                        dataType: 'json',
                        success: function (json) {
                            if (json.success)
                                data = JSON.parse(json.data.value);
                        }
                    });
                    return data;
                },
                stateSaveCallback: function (settings, data) {
                    $.ajax({
                        type: "POST",
                        url: "{{ urlFor("user.pref") }}",
                        data: {
                            preference: [{
                                option: "playlistGrid",
                                value: JSON.stringify(data)
                            }]
                        }
                    });
                },
                filter: false,
                searchDelay: 3000,
                "order": [[1, "asc"]],
                ajax: {
                    url: "{{ urlFor("playlist.search") }}",
                    "data": function (d) {
                        $.extend(d, $("#playlists").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                    }
                },
                "columns": [
                    {"data": "playlistId"},
                    {
                        "data": "name",
                        "render": dataTableSpacingPreformatted
                    },
                    {
                        "data": "duration",
                        "render": function (data, type, row) {
                            if (type !== "display" && type !== "export")
                                return data;

                            if (row.requiresDurationUpdate === 1) {
                                return '<span class="fa fa-clock-o" title="{{ "Changes have been made and we are recalculating this Playlists duration" }}"></span>';
                            } else if (row.requiresDurationUpdate !== 0) {
                                return moment().startOf("day").seconds(data).format("H:mm:ss") + ' <span class="fa fa-clock-o" title="{{ "This duration will be updated at " }}' + moment(row.requiresDurationUpdate, "X").format(jsDateFormat) + '"></span>';
                            }

                            return moment().startOf("day").seconds(data).format("H:mm:ss");
                        }
                    },
                    {
                        "sortable": false,
                        "visible": false,
                        "data": dataTableCreateTags
                    },
                    { "data": "isDynamic", "render": dataTableTickCrossColumn },
                    {"data": "owner"},
                    {
                        "data": "groupsWithPermissions",
                        "render": dataTableCreatePermissions
                    },
                    {
                        "data": "createdDt",
                        "render": dataTableDateFromIso,
                        "visible": false
                    },
                    {
                        "data": "modifiedDt",
                        "render": dataTableDateFromIso,
                        "visible": false
                    },
                    {
                        "name": "enableStat",
                        "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>";
                        }
                    },
                    {
                        "orderable": false,
                        "data": dataTableButtonsColumn
                    }
                ]
            });

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

        // Playlist Add Form
        // contains a grid on the populate tab
        // hook up the grid
        var mediaTable;
        var nameFilter;
        var tagFilter;

        function playlistEditorFormOpen(formData) {

            // Clear container
            $('#editor-container').empty();

            // Append form
            $('#editor-container').append(formData.message);
        }

        function playlistFormOpen(dialog) {
            mediaTable = null;

            $(dialog).find("input[name=filterMediaName]").on("keyup", _.debounce(function() {
                playlistFormPopulateMediaTable(dialog);
            }, 500));

            $(dialog).find("input[name=filterMediaTag]").on("change", function() {
                playlistFormPopulateMediaTable(dialog);
            });

            // First time in there
            playlistFormPopulateMediaTable(dialog);
        }

        function playlistFormPopulateMediaTable(dialog) {

            nameFilter = $(dialog).find("input[name=filterMediaName]").val();
            tagFilter = $(dialog).find("input[name=filterMediaTag]").val();

            if (nameFilter === "" && tagFilter === "") {
                if (mediaTable != null) {
                    mediaTable.destroy();
                    mediaTable = null;
                    $("#playlistLibraryMedia tbody").empty();
                }

                return;
            }

            if (mediaTable != null) {
                mediaTable.ajax.reload();
            } else {
                mediaTable = $("#playlistLibraryMedia").DataTable({
                    "language": dataTablesLanguage,
                    serverSide: true,
                    stateSave: true,
                    stateDuration: 0,
                    filter: false,
                    searchDelay: 3000,
                    "order": [[1, "asc"]],
                    ajax: {
                        "url": "{{ urlFor("library.search") }}",
                        "data": function (d) {
                            $.extend(d, {media: nameFilter, tags: tagFilter, assignable:1});
                        }
                    },
                    "columns": [
                        {"data": "mediaId"},
                        {"data": "name"},
                        {"data": "mediaType"},
                        {"data": dataTableCreateTags},
                        {
                            "name": "duration",
                            "data": function (data, type) {
                                if (type !== "display")
                                    return data.duration;

                                return moment().startOf("day").seconds(data.duration).format("H:mm:ss");
                            }
                        }
                    ]
                });

                mediaTable.on('processing.dt', dataTableProcessing);
                mediaTable.on('draw', { form: $(".playlistForm") }, dataTableCreateTagEvents);
            }
        }

        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>

    {% for module in modules %}
        {% if module.layoutDesignerJavaScript() != "" %}
            {% include module.layoutDesignerJavaScript() ~ ".twig" %}
        {% endif %}
    {% endfor %}

{% endblock %}