{#
/**
 * Copyright (C) 2018 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" title="{% trans "Add RSS" %}" href="{{ urlFor("dataSet.rss.add.form", {id: dataSet.dataSetId}) }}"><i class="fa fa-plus-circle" aria-hidden="true"></i> {% trans "Add RSS" %}</a></li>
    </ul>
{% endblock %}

{% block pageContent %}
    {% set dataSetName = dataSet.dataSet %}
    {% set widgetTitle %}{% trans %}RSS Feeds for {{ dataSetName }}{% endtrans %}{% endset %}
    <div class="widget">
        <div class="widget-title">{{ widgetTitle }}</div>
        <div class="widget-body">
            <div class="XiboGrid" id="{{ random() }}">
                <div class="XiboFilter">
                    <div class="FilterDiv" id="Filter">
                        <form class="form-inline">

                        </form>
                    </div>
                </div>
                <div class="XiboData">
                    <table id="datasets" class="table table-striped">
                        <thead>
                            <tr>
                                <th>{% trans "ID" %}</th>
                                <th>{% trans "Title" %}</th>
                                <th>{% trans "Author" %}</th>
                                <th>{% trans "URL" %}</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>

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

{% block javaScript %}
    <script type="text/javascript">
        var table = $("#datasets").DataTable({
            "language": dataTablesLanguage,
            serverSide: true,
            stateSave: true,
            stateDuration: 0,
            stateLoadCallback: function (settings, callback) {
                var data;
                $.ajax({
                    type: "GET",
                    async: false,
                    url: "{{ urlFor("user.pref") }}?preference=dataSetRssGrid",
                    dataType: 'json',
                    success: function (json) {
                        try {
                            if (json.success) {
                                data = JSON.parse(json.data.value);
                            }
                        } catch (e) {
                            // Do nothing
                        }
                    }
                });
                return data;
            },
            stateSaveCallback: function (settings, data) {
                $.ajax({
                    type: "POST",
                    url: "{{ urlFor("user.pref") }}",
                    data: {
                        preference: [{
                            option: "dataSetColumnGrid",
                            value: JSON.stringify(data)
                        }]
                    }
                });
            },
            filter: false,
            searchDelay: 3000,
            "order": [[ 0, "asc"]],
            ajax: {
                "url": "{{ urlFor("dataSet.rss.search", {id: dataSet.dataSetId}) }}",
                "data": function(d) {
                    $.extend(d, $("#datasets").closest(".XiboGrid").find(".FilterDiv form").serializeObject());
                }
            },
            "columns": [
                { "data": "id" },
                { "data": "title" },
                { "data": "author" },
                {
                    "orderable": false,
                    "data": function (data, type, row, meta) {
                        if (type !== "display")
                            return "";

                        var url = window.location.origin + "{{ urlFor("dataSet.rss.feed") }}".replace(':psk', data.psk);

                        return "<a href=\"" + url + "\" target=\"_blank\">" + url + "</a>";
                    }
                },
                {
                    "orderable": false,
                    "data": dataTableButtonsColumn
                }
            ]
        });

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

        /**
         * Configure the Query Building on DataSetRss Add/Edit forms.
         * @param dialog
         */
        function configureQueryBuilder(dialog) {
            // Order Clause
            var orderClauseFields = $("#orderClause");

            if (orderClauseFields.length === 0)
                return;

            var orderClauseTemplate = Handlebars.compile($("#dataSetViewOrderClauseTemplate").html());
            var ascTitle = "{% trans "Ascending" %}";
            var descTitle = "{% trans "Descending" %}";

            if (dialog.data().extra.orderClauses.length === 0) {
                // Add a template row
                var context = {columns: dialog.data().extra.columns, title: "1", orderClause: "", orderClauseAsc: "", orderClauseDesc: "", buttonGlyph: "fa-plus", ascTitle: ascTitle, descTitle: descTitle};
                orderClauseFields.append(orderClauseTemplate(context));
            } else {
                // For each of the existing codes, create form components
                var i = 0;
                $.each(dialog.data().extra.orderClauses, function (index, field) {
                    i++;

                    var direction = (field.orderClauseDirection === "ASC");

                    var context = {columns: dialog.data().extra.columns, title: i, orderClause: field.orderClause, orderClauseAsc: direction, orderClauseDesc: !direction, buttonGlyph: ((i == 1) ? "fa-plus" : "fa-minus"), ascTitle: ascTitle, descTitle: descTitle};

                    orderClauseFields.append(orderClauseTemplate(context));
                });
            }

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

                // find the gylph
                if ($(this).find("i").hasClass("fa-plus")) {
                    var context = {columns: dialog.data().extra.columns, title: orderClauseFields.find('.form-group').length + 1, orderClause: "", orderClauseAsc: "", orderClauseDesc: "", buttonGlyph: "fa-minus", ascTitle: ascTitle, descTitle: descTitle};
                    orderClauseFields.append(orderClauseTemplate(context));
                } else {
                    // Remove this row
                    $(this).closest(".form-group").remove();
                }
            });

            //
            // Filter Clause
            //
            var filterClauseFields = $("#filterClause");
            var filterClauseTemplate = Handlebars.compile($("#dataSetViewFilterClauseTemplate").html());
            var filterOptions = [
                {
                    id: "starts-with",
                    value: "{% trans "starts with" %}"
                },{
                    id: "ends-with",
                    value: "{% trans "ends with" %}"
                },{
                    id: "contains",
                    value: "{% trans "contains" %}"
                },{
                    id: "equals",
                    value: "{% trans "equals" %}"
                },{
                    id: "not-starts-with",
                    value: "{% trans "does not start with" %}"
                },{
                    id: "not-ends-with",
                    value: "{% trans "does not end with" %}"
                },{
                    id: "not-contains",
                    value: "{% trans "does not contain" %}"
                },{
                    id: "not-equals",
                    value: "{% trans "does not equal" %}"
                },{
                    id: "greater-than",
                    value: "{% trans "greater than" %}"
                },{
                    id: "less-than",
                    value: "{% trans "less than" %}"
                },{
                    id: "is-empty",
                    value: "{% trans "is empty" %}"
                },{
                    id: "is-not-empty",
                    value: "{% trans "is not empty" %}"
                }
            ];
            var filterOperatorOptions = [
                {
                    id: "OR",
                    value: "{% trans "Or" %}"
                },{
                    id: "AND",
                    value: "{% trans "And" %}"
                }
            ];

            if (dialog.data().extra.filterClauses.length == 0) {
                // Add a template row
                context = {
                    columns: dialog.data().extra.columns,
                    filterOptions: filterOptions,
                    filterOperatorOptions: filterOperatorOptions,
                    title: "1",
                    filterClause: "",
                    filterClauseOperator: "AND",
                    filterClauseCriteria: "",
                    filterClauseValue: "",
                    buttonGlyph: "fa-plus"
                };
                filterClauseFields.append(filterClauseTemplate(context));
            } else {
                // For each of the existing codes, create form components
                var j = 0;
                $.each(dialog.data().extra.filterClauses, function (index, field) {
                    j++;

                    var context = {
                        columns: dialog.data().extra.columns,
                        filterOptions: filterOptions,
                        filterOperatorOptions: filterOperatorOptions,
                        title: j,
                        filterClause: field.filterClause,
                        filterClauseOperator: field.filterClauseOperator,
                        filterClauseCriteria: field.filterClauseCriteria,
                        filterClauseValue: field.filterClauseValue,
                        buttonGlyph: ((j == 1) ? "fa-plus" : "fa-minus")
                    };

                    filterClauseFields.append(filterClauseTemplate(context));
                });
            }

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

                // find the gylph
                if ($(this).find("i").hasClass("fa-plus")) {
                    var context = {
                        columns: dialog.data().extra.columns,
                        filterOptions: filterOptions,
                        filterOperatorOptions: filterOperatorOptions,
                        title: filterClauseFields.find('.form-group').length + 1,
                        filterClause: "",
                        filterClauseOperator: "AND",
                        filterClauseCriteria: "",
                        filterClauseValue: "",
                        buttonGlyph: "fa-minus"
                    };
                    filterClauseFields.append(filterClauseTemplate(context));
                } else {
                    // Remove this row
                    $(this).closest(".form-group").remove();
                }
            });
        }

        Handlebars.registerHelper('if_eq', function(a, b, opts) {
            if(a == b) // Or === depending on your needs
                return opts.fn(this);
            else
                return opts.inverse(this);
        });
    </script>

    {% raw %}
        <script type="text/x-handlebars-template" id="dataSetViewOrderClauseTemplate">
            <div class="form-group">
                <label class="col-sm-1 control-label" for="orderClause[]">{{ title }}</label>
                <div class="col-sm-7">
                    <select class="form-control" name="orderClause[]">
                        <option value=""></option>
                        {{#each columns}}
                        <option value="{{ heading }}" {{#if_eq heading ../orderClause}}selected{{/if_eq}}>{{ heading }}</option>
                        {{/each}}
                    </select>
                </div>
                <div class="col-sm-3">
                    <label for="orderClauseDirection[]">
                        <select class="form-control" name="orderClauseDirection[]">
                            <option value="ASC" {{#if orderClauseAsc}}selected{{/if}}>{{ ascTitle }}</option>
                            <option value="DESC" {{#if orderClauseDesc}}selected{{/if}}>{{ descTitle }}</option>
                        </select>
                    </label>
                </div>
                <div class="col-sm-1">
                    <button class="btn btn-default btn-sm"><i class="fa {{ buttonGlyph }}"></i></button>
                </div>
            </div>
        </script>

        <script type="text/x-handlebars-template" id="dataSetViewFilterClauseTemplate">
            <div class="form-group">
                <label class="col-sm-1 control-label" for="filterClause[]">{{ title }}</label>
                <div class="col-sm-2">
                    <label for="filterClauseOperator[]" {{#if_eq title "1"}}class="hidden"{{/if_eq}}>
                    <select class="form-control" name="filterClauseOperator[]">
                        {{#each filterOperatorOptions}}
                        <option value="{{ id }}" {{#if_eq id ../filterClauseOperator}}selected{{/if_eq}}>{{ value }}</option>
                        {{/each}}
                    </select>
                    </label>
                </div>
                <div class="col-sm-3">
                    <select class="form-control" name="filterClause[]">
                        <option value=""></option>
                        {{#each columns}}
                        <option value="{{ heading }}" {{#if_eq heading ../filterClause}}selected{{/if_eq}}>{{ heading }}</option>
                        {{/each}}
                    </select>
                </div>
                <div class="col-sm-3">
                    <label for="filterClauseCriteria[]">
                        <select class="form-control" name="filterClauseCriteria[]">
                            {{#each filterOptions}}
                            <option value="{{ id }}" {{#if_eq id ../filterClauseCriteria}}selected{{/if_eq}}>{{ value }}</option>
                            {{/each}}
                        </select>
                    </label>
                </div>
                <div class="col-sm-2">
                    <label for="filterClauseValue[]">
                        <input class="form-control" name="filterClauseValue[]" type="text" value="{{ filterClauseValue }}" />
                    </label>
                </div>
                <div class="col-sm-1">
                    <button class="btn btn-default btn-sm"><i class="fa {{ buttonGlyph }}"></i></button>
                </div>
            </div>
        </script>

    {% endraw %}
{% endblock %}