{% extends "@UVDeskCore/Templates/layout.html.twig" %}

{% block title %}Swift Mailer List{% endblock %}

{% block templateCSS %}
    <style>
		.uv-action-bar {
			border-bottom: 1px solid #d3d3d3;
			padding-bottom: 10px;
		}
	</style>
{% endblock %}

{% block pageContent %}
	<div class="uv-inner-section">
        {# Setting Panel Sidebar #}
        {{ include('@UVDeskCore/Templates/panel-sidebar.html.twig') }}

		<div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
			<h1>Swift Mailer</h1>

            {# Ticket Types Action Bar #}
			<div class="uv-action-bar">
                <div class="uv-action-bar-col-lt">
       
                </div>

				<div class="uv-action-bar-col-rt">
					{# <input type="text" class="uv-search-inline uv-vertical-align uv-margin-right-15" placeholder="{{ 'Search'|trans }}"> #}
					<a href="{{ path('helpdesk_member_swiftmailer_create_mailer') }}" type="button" class="uv-btn-action"><span class="uv-icon-add"></span>Add New</a>
				</div>
            </div>

            <div class="uv-table uv-list-view">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Transport</th>
                            <th class="uv-last">Action</th>
                        </tr>
                    </thead>

                    <tbody></tbody>
                </table>

				<div class="navigation"></div>
            </div>
		</div>
	</div>
{% endblock %}

{% block footer %}
	{{ parent() }}

	<!-- Sorting Template -->
	<script id="type_list_sorting_tmp" type="text/template">
        <li class="<% if(sort == 'ticketType.id') { %>uv-drop-list-active<% } %>">
            <a href="#<% if(queryString != '') { %><%= queryString %>/<% } %><% if(page) { %>page/<%= page %><% } else { %>page/1<% } %>/sort/ticketType.id/<% if(sort == 'ticketType.id') { %><% if(direction) { %>direction/<%= direction %><% } else { %>direction/desc<% } %><% } else { %>direction/asc<% } %>" data-field="ticketType.id">
                {{ 'Id'|trans }}
            </a>
            <% if(sort == 'ticketType.id') { %>
                <span class="uv-sorting <% if(direction == 'asc') { %> descend <% } else { %> ascend <% } %>"></span>

            <% } %>
        </li>
        <li class="<% if(sort == 'ticketType.code') { %>uv-drop-list-active<% } %>">
            <a href="#<% if(queryString != '') { %><%= queryString %>/<% } %><% if(page) { %>page/<%= page %><% } else { %>page/1<% } %>/sort/ticketType.code/<% if(sort == 'ticketType.code') { %><% if(direction) { %>direction/<%= direction %><% } else { %>direction/desc<% } %><% } else { %>direction/asc<% } %>" data-field="ticketType.code">
                {{ 'Code'|trans }}
            </a>
            <% if(sort == 'ticketType.code') { %>
                <span class="uv-sorting <% if(direction == 'asc') { %> descend <% } else { %> ascend <% } %>"></span>

            <% } %>
        </li>
	</script>
	<!-- //Sorting Template -->

	<!-- Type list item template -->
	<script id="type_list_item_tmp" type="text/template">
		<td data-value="{{ 'Name'|trans }}"><%- id %></td>
		<td data-value="{{ 'Email'|trans }}"><%-  username %></td>
		<td data-value="{{ 'Transport'|trans }}"><%-  transport %></td>

		<td data-value="{{ 'Action'|trans }}" class="uv-last">
			<a href="<%= path.replace('replaceId', id) %>" class="uv-btn-stroke edit-type">
				{{ "Edit"|trans }}
			</a>
			<div class="uv-btn-stroke delete-type">
				{{ "Delete"|trans }}
			</div>
		</td>
    </script>
	<!-- //Type list item template -->

	<script type="text/javascript">
		var path = "{{ path('helpdesk_member_swiftmailer_update_mailer', {'swiftmailerId': 'replaceId' }) }}";

		$(function () {
			var globalMessageResponse = "";

			var TypeModel = Backbone.Model.extend({
				idAttribute : "id"
			});

			var TypeCollection = AppCollection.extend({
				model : TypeModel,
				url : "{{ path('helpdesk_member_swiftmailer_settings_xhr') }}",
				filterParameters : {
					"isActive" : "",
					"search" : ""
				},
				parseRecords: function (resp, options) {
					return resp.types;
				},
				syncData : function() {
					app.appView.showLoader();
					this.fetch({
						data : this.getValidParameters(),
						reset: true,
						success: function(model,response) {
							app.appView.hideLoader();
							var typeListView = new TypeList(response);
							app.pager.paginationData = response.pagination_data;

							//var url = app.pager.paginationData.url;
							{# if(typeCollection.length == 0 && app.pager.paginationData.current != "0")
								router.navigate(url.replace('replacePage', app.pager.paginationData.last),{trigger: true});
							else {
								app.pager.render();
							} #}
							if(globalMessageResponse)
								app.appView.renderResponseAlert(globalMessageResponse);
							globalMessageResponse = null;
						},
						error: function (model, xhr, options) {
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
						}
					});
				}
			});

			var TypeItem = Backbone.View.extend({
				tagName : "tr",
				template : _.template($("#type_list_item_tmp").html()),
				events : {
					'click .delete-type' : "confirmRemove"
				},
				render : function() {
					this.$el.html(this.template(this.model));
					return this;
				},
				unrender : function(response) {
					if(response.alertMessage != undefined) {
						typeCollection.syncData();
						app.appView.renderResponseAlert(response)
					}
				},
				confirmRemove: function(e) {
					e.preventDefault();
					app.appView.openConfirmModal(this)
				},
				removeItem : function (e) {
					app.appView.showLoader();
					self = this;
					
					$.ajax({
						url: "{{ path('helpdesk_member_swiftmailer_remove_mailer_xhr') }}?id="+this.model.id,
						success : function (response) {
							app.appView.hideLoader();
							globalMessageResponse = response;
							typeCollection.syncData();
						},
						error: function (model, xhr, options) {
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
							var response = warningResponse;
							if(xhr.responseJSON)
								response = xhr.responseJSON;

							app.appView.hideLoader();
							app.appView.renderResponseAlert(response);
						}
					});
					{# this.model.destroy({
						url : "{{ path('helpdesk_member_swiftmailer_remove_mailer_xhr') }}/"+this.model.id,
						success : function (model, response, options) {
							app.appView.hideLoader();
							globalMessageResponse = response;
							typeCollection.syncData();
						},
						error: function (model, xhr, options) {
							if(url = xhr.getResponseHeader('Location'))
								window.location = url;
							var response = warningResponse;
							if(xhr.responseJSON)
								response = xhr.responseJSON;

							app.appView.hideLoader();
							app.appView.renderResponseAlert(response);
						}
					}); #}
				}
			});

			var TypeList = Backbone.View.extend({
				el : $(".uv-list-view table tbody"),
				initialize : function(listItems) {
					this.render(listItems);
				},
				render : function (items) {
					this.$el.find("tr").remove();
					if(items) {
						_.each(items, function (item, key) {
							item['id'] = key;
							this.renderType(item);
						}, this);
					} else {
						this.$el.append("<tr style='text-align: center;'><td colspan='4'>{% trans %}No Record Found{% endtrans %}</td></tr>")
					}
				},
				renderType : function (item) {
					var typeItem = new TypeItem({
						model: item
					});
					this.$el.append(typeItem.render().el);
				}
			});

			var Filter = app.Filter.extend({
				defaultSortIndex: 'a.id',
				sortText: "{% trans %}Sort By:{% endtrans %} ",
				defaultSortText: "{% trans %}Sort By:{% endtrans %} {% trans %}Id{% endtrans %}",
				template : _.template($("#type_list_sorting_tmp").html())
			})

			var typeCollection = new TypeCollection();

			var filter = new Filter({
				collection : typeCollection
			});

			Router = Backbone.Router.extend({
				routes: {
					'page/:number(/sort/:sortField)(/direction/:order)' : 'paginate',
					'isActive/:status(/search/:query)(/page/:number)(/sort/:sortField)(/direction/:order)' : 'filterTypeList',
					'search/:query(/page/:number)(/sort/:sortField)(/direction/:order)' : 'filterByQuery',
					'' : 'initializeList'
				},
				initializeList : function() {
					this.resetParams('', '');
					typeCollection.state.currentPage = null;
					filter.sortCollection();
					typeCollection.syncData();
				},
				paginate : function(number,sortField,order) {
					this.resetParams('', '');
					typeCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					typeCollection.syncData();
				},
				filterTypeList: function(status,query,number,sortField,order) {
					this.resetParams(status,query);
					typeCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					typeCollection.syncData();
				},
				filterByQuery : function(query,number,sortField,order) {
					this.resetParams('',query);
					typeCollection.state.currentPage = number;
					filter.sortCollection(sortField,order);
					typeCollection.syncData();
				},
				resetParams : function(status, query) {
					if(query != null)
						query = query.replace(/\+/g,' ');
					typeCollection.filterParameters.isActive = status;
					var statusText = status ? $(".filter-by-status a[data-id='" + status + "']").text() : "{% trans %}All{% endtrans %}";
					$(".filter-by-status .uv-dropdown-btn").text("{% trans %}Status:{% endtrans %} " + statusText);
					typeCollection.filterParameters.search = query;
					$(".uv-search-inline").val(query);
				}
			});

			router = new Router();
			Backbone.history.start({push_state:true});


			var typeItem = new TypeItem({
				model: new TypeModel()
			});
		});
	</script>
{% endblock %}