{#
/**
 * 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/>.
 */
#}
{% extends "authed.twig" %}
{% import "inline.twig" as inline %}

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

{% block actionMenu %}
    <div class="widget-action-menu pull-right">
        {% if currentUser.featureEnabled("daypart.add") %}
            <button class="btn btn-success XiboFormButton" href="{{ url_for("daypart.add.form") }}"><i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add Daypart" %}</button>
        {% 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 "Dayparting" %}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}">
                <div class="XiboFilter card mb-3 bg-light">
                    <div class="FilterDiv card-body" id="Filter">
                        <form class="form-inline">
                            {% set title %}{% trans "Name" %}{% endset %}
                            {{ inline.inputNameGrid('name', title) }}

                            {% 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("isRetired", "single", title, 0, values, "id", "value") }}
                        </form>
                    </div>
                </div>
                <div class="XiboData card pt-3">
                    <table id="dayparts" class="table table-striped" data-state-preference-name="daypartGrid">
                        <thead>
                            <tr>
                                <th>{% trans "Name" %}</th>
                                <th>{% trans "Description" %}</th>
                                <th>{% trans "Start Time" %}</th>
                                <th>{% trans "End Time" %}</th>
                                <th class="rowMenu"></th>
                            </tr>
                        </thead>
                        <tbody>

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

{% block javaScript %}
    <script type="text/javascript" nonce="{{ cspNonce }}">

        var table = $("#dayparts").DataTable({
            "language": dataTablesLanguage,
            dom: dataTablesTemplate,
            serverSide: true,
            stateSave: true,
            stateDuration: 0,
            responsive: true,
            stateLoadCallback: dataTableStateLoadCallback,
            stateSaveCallback: dataTableStateSaveCallback,
            filter: false,
            searchDelay: 3000,
            "order": [[ 1, "asc"]],
            ajax: {
                "url": "{{ url_for("daypart.search") }}",
                "data": function(d) {
                    $.extend(d, $("#dayparts").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                }
            },
            "columns": [
                { "data": "name", "render": dataTableSpacingPreformatted , responsivePriority: 2},
                { "data": "description" },
                { "data": "startTime" },
                { "data": "endTime" },
                {
                    "orderable": false,
                    responsivePriority: 1,
                    "data": dataTableButtonsColumn
                }
            ]
        });

        table.on('draw', dataTableDraw);
        table.on('processing.dt', dataTableProcessing);
        dataTableAddButtons(table, $('#dayparts_wrapper').find('.dataTables_buttons'));

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

        function dayPartFormOpen(dialog) {
            // Render a set of exceptions
            $exceptions = $(dialog).find("#dayPartExceptions");

            // Days of the week translations
            var daysOfTheWeek = [
                { day: "Mon", title: "{% trans "Monday" %}" },
                { day: "Tue", title: "{% trans "Tuesday" %}" },
                { day: "Wed", title: "{% trans "Wednesday" %}" },
                { day: "Thu", title: "{% trans "Thursday" %}" },
                { day: "Fri", title: "{% trans "Friday" %}" },
                { day: "Sat", title: "{% trans "Saturday" %}" },
                { day: "Sun", title: "{% trans "Sunday" %}" }
            ];

            // Compile the handlebars template
            var exceptionsTemplate = Handlebars.compile($("#dayPartExceptionsTemplate").html());

            if (dialog.data().extra.exceptions.length == 0) {
                // Contexts for template
                var context = {
                    daysOfWeek: daysOfTheWeek,
                    buttonGlyph: "fa-plus",
                    exceptionDay: "",
                    exceptionStart: "",
                    exceptionEnd: "",
                    fieldId: 0
                };

                // Append
                $exceptions.append(exceptionsTemplate(context));
                
                XiboInitialise("#" + $exceptions.prop("id"));
            } else {
                // For each of the existing exceptions, create form components
                var i = 0;
                $.each(dialog.data().extra.exceptions, function (index, field) {
                    i++;
                    // call the template
                    var context = {
                        daysOfWeek: daysOfTheWeek,
                        buttonGlyph: ((i == 1) ? "fa-plus" : "fa-minus"),
                        exceptionDay: field.day,
                        exceptionStart: field.start,
                        exceptionEnd: field.end,
                        fieldId: i
                    };

                    $exceptions.append(exceptionsTemplate(context));
                    
                    XiboInitialise("#" + $exceptions.prop("id"));
                });
            }

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

                // find the gylph
                if ($(this).find("i").hasClass("fa-plus")) {
                    var context = {
                        daysOfWeek: daysOfTheWeek,
                        buttonGlyph: "fa-minus",
                        exceptionDay: "",
                        exceptionStart: "",
                        exceptionEnd: "",
                        fieldId: $exceptions.find('.form-group').length + 1
                    };

                    $exceptions.append(exceptionsTemplate(context));

                    XiboInitialise("#" + $exceptions.prop("id"));
                } else {
                    // Remove this row
                    $(this).closest(".form-group").remove();
                }
            });

            // check if we already have this day in exceptions array, if so remove the row with a message.
            $exceptions.on("change", "select", function() {
                var selectedDays = [];
                $('select').not('#' + $(this).attr('id')).each(function(i) {
                    selectedDays.push($(this).val());
                });

                if (selectedDays.includes(this.value)) {
                    toastr.error(translations.dayPartExceptionErrorMessage);
                    // Remove this row
                    $(this).closest(".form-group").remove();
                }
            })
        }

        // Equals helper for the templates below
        Handlebars.registerHelper('eq', function(v1, v2, opts) {
            if (v1 === v2) {
                return opts.fn(this);
            } else {
                return opts.inverse(this);
            }
        });
    </script>
    {% verbatim %}
    <script type="text/x-handlebars-template" id="dayPartExceptionsTemplate">
        <div class="form-group row">
            <div class="col-3">
                <select class="form-control" name="exceptionDays[]" id="exceptionDays_{{fieldId}}">
                    <option value=""></option>
                    {{#each daysOfWeek}}
                    <option value="{{ day }}" {{#eq day ../exceptionDay}}selected{{/eq}}>{{ title }}</option>
                    {{/each}}
                </select>
            </div>
            <div class="col-3">
    {% endverbatim %}
                {{ inline.time("exceptionStartTimes[]", "", "{{ exceptionStart }}"  ) }}
    {% verbatim %}
            </div>
            <div class="col-3">
    {% endverbatim %}
                {{ inline.time("exceptionEndTimes[]", "", "{{ exceptionEnd }}"  ) }}
    {% verbatim %}
            </div>
            <div class="col-1">
                <button class="btn btn-white"><i class="fa {{ buttonGlyph }}"></i></button>
            </div>
        </div>
    </script>
    {% endverbatim %}
{% endblock %}