{#
/**
 * Copyright (C) 2020 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/>.
 */
#}

<script type="text/javascript">

    // Runs after form opens
    function subplaylist_form_edit_open() {

        // Get form object
        var $dialog = $(this);
        var $form = $dialog.find('form');

        // setup checkbox behaviour for cycle based playback
        formHelpers.setupCheckboxInputFields($form, '#cyclePlaybackEnabled', '.cycle-based-playback');

        // Bind our tooltips
        $form.find('[data-toggle="tooltip"]').tooltip();

        // Translations
        var fillTitle = "{% trans "Fill" %}";
        var fillHelpText = "{% trans "Fill - use the first Playlist to fill any remaining Spots" %}";
        var padTitle = "{% trans "Pad" %}";
        var padHelpText = "{% trans "Pad - use the first Playlist to pad any remaining Spots" %}";
        var repeatTitle = "{% trans "Repeat" %}";
        var repeatHelpText = "{% trans "Repeat - repeat the Widgets in this Playlist until the number of Spots have been filled" %}";

        // Order Clause
        var subPlaylistFields = $(".sub-playlists", $form);

        // Get template
        var subPlaylistFormTemplate = formHelpers.getTemplate('subPlaylistFormTemplate');

        if(subPlaylistFields.length === 0) {
            return;
        }

        if($dialog.data().extra.subPlaylists.length === 0) {
            // Add a template row
            subPlaylistFields.append(subPlaylistFormTemplate({
                title: "1",
                subPlaylistId: "",
                subPlaylistIdSpots: "",
                subPlaylistIdSpotLength: "",
                subPlaylistIdSpotFill: "",
                buttonGlyph: "fa-plus",
                fillTitle: fillTitle,
                padTitle: padTitle,
                repeatTitle: repeatTitle,
                fillHelpText: fillHelpText,
                padHelpText: padHelpText,
                repeatHelpText: repeatHelpText,
            }));
        } else {
            // For each of the existing codes, create form components
            $.each($dialog.data().extra.subPlaylists, function(index, field) {
                subPlaylistFields.append(subPlaylistFormTemplate({
                    title: field.rowNo,
                    subPlaylistId: field.playlistId,
                    subPlaylistIdSpots: field.spots,
                    subPlaylistIdSpotLength: field.spotLength,
                    subPlaylistIdSpotFill: field.spotFill,
                    buttonGlyph: ((field.rowNo === 1) ? 'fa-plus' : 'fa-minus'),
                    fillTitle: fillTitle,
                    padTitle: padTitle,
                    repeatTitle: repeatTitle,
                    fillHelpText: fillHelpText,
                    padHelpText: padHelpText,
                    repeatHelpText: repeatHelpText,
                }));
            });
        }

        // Nabble the resulting buttons
        subPlaylistFields.on("click", "button", function(e) {
            e.preventDefault();

            // find the gylph
            if($(this).find("i").hasClass("fa-plus")) {
                var $newRow = $(subPlaylistFormTemplate({
                    title: subPlaylistFields.find('.row-special').length + 1,
                    subPlaylistId: "",
                    subPlaylistIdSpots: "",
                    subPlaylistIdSpotLength: "",
                    subPlaylistIdSpotFill: "",
                    buttonGlyph: "fa-minus",
                    fillTitle: fillTitle,
                    padTitle: padTitle,
                    repeatTitle: repeatTitle,
                    fillHelpText: fillHelpText,
                    padHelpText: padHelpText,
                    repeatHelpText: repeatHelpText,
                }));
                subPlaylistFields.append($newRow);

                subplaylist_init_row($form, $newRow);
            } else {
                // Remove this row
                $(this).closest(".row-special").remove();
            }
        });

        subPlaylistFields.find('.row').each(function(index, element) {
            subplaylist_init_row($form, $(element));
        });
    }

    function subplaylist_init_row($form, $row) {
        var $select = $row.find('.subPlaylistSelect');

        // Get the initial value.
        if ($select.data('fieldId')) {
            $.ajax({
                method: 'GET',
                url: '{{ url_for("playlist.search") }}?playlistId=' + $select.data('fieldId'),
                success: function (response) {
                    if (response.data && response.data.length > 0) {
                        // Append our initial option
                        $select.append('<option value="' + response.data[0].playlistId +
                            '" data-tags="' + response.data[0].tags +
                            '" selected>' + response.data[0].name + '</option>');

                        subplaylist_init_select2($form, $select);
                    } else {
                        // No permissions.
                        $select.parent().append('<input type="hidden" value="' + $select.data('fieldId') + '" name="subPlaylistId[]">' +
                            '<span title="{% trans "You do not have access to this playlist" %}"><i class="fa fa-lock"></i>&nbsp;{% trans "Playlist Id " %}' +
                            $select.data('fieldId') + '</span>');
                        $select.remove();
                    }
                },
                error: function () {
                    $select.parent().append('{% trans "An unknown error has occurred. Please refresh" %}');
                }
            });
        } else {
            subplaylist_init_select2($form, $select);
        }

        $row.find('select[name="subPlaylistIdSpotFill[]"]').select2({
            templateResult: function(state) {
                if (!state.id) {
                    return state.text;
                }
                return $(state.element).data().templateResult;
            },
            dropdownAutoWidth: true,
            minimumResultsForSearch: -1
        });
    }

    function subplaylist_init_select2($form, $el) {
        $el.select2({
            dropdownAutoWidth: true,
            ajax: {
                url: '{{ url_for("playlist.search") }}?notPlaylistId=' + $form.data('playlistId'),
                dataType: 'json',
                data: function (params) {
                    var query = {
                        start: 0,
                        length: 10,
                        name: params.term
                    };
                    if (params.page != null) {
                        query.start = (params.page - 1) * 10;
                    }
                    return query;
                },
                processResults: function (data, params) {
                    var results = [];

                    $.each(data.data, function (index, el) {
                        results.push({
                            id: el.playlistId,
                            text: el.name,
                        });
                    });

                    var page = params.page || 1;
                    page = (page > 1) ? page - 1 : page;

                    if (page === 1 && results.length <= 0) {
                        $form.find('.sub-playlist-no-playlists-message').removeClass('d-none');
                    }

                    return {
                        results: results,
                        pagination: {
                            more: (page * 10 < data.recordsTotal)
                        }
                    };
                }
            },
        });
    }

</script>
