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

{% block title %}{{ 'Add Group'|trans }}{% endblock %}

{% block pageContent %}
	<div class="uv-inner-section">
		{# Append Panel Aside #}
		{% set asideTemplate = 'Webkul\\UVDesk\\CoreFrameworkBundle\\Dashboard\\AsideTemplate' %}
		{% set asideSidebarReference = 'Webkul\\UVDesk\\CoreFrameworkBundle\\UIComponents\\Dashboard\\Panel\\Sidebars\\Users' %}

		{{ uvdesk_extensibles.getRegisteredComponent(asideTemplate).renderSidebar(asideSidebarReference) | raw }}
		
		<div class="uv-view {% if app.request.cookies and app.request.cookies.get('uv-asideView') %}uv-aside-view{% endif %}">
			<h1>{{ 'Add Group'|trans }}</h1>
			
			<!--Form-->
			<form method="post" action="" id="group-form">
				<!-- Field -->
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Name'|trans }}</label>
					<div class="uv-field-block">
						<input type="text" name="name" class="uv-field" value="{{ group.name }}" />
					</div>
				</div>
				<!-- //Field -->

				<!-- Field -->
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Description'|trans }}</label>
					<div class="uv-field-block">
						<textarea name="description" class="uv-field">{{ group.description }}</textarea>
					</div>
				</div>
				<!-- //Field -->

                <!-- Field -->
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Users'|trans }}</label>
					<div class="uv-field-block" id="agent-filter">
						<input type="hidden" name="tempUsers" class="uv-field" value="" />
                        <input class="uv-field uv-dropdown-other preloaded" type="text" id="user-filter-input">
                        <div class="uv-dropdown-list uv-bottom-left">
                            <div class="uv-dropdown-container">
                                <label>{{ 'Filter With'|trans }}</label>
                            </div>
                            <ul class="uv-agents-list">
                                {% for agent in user_service.getAgentsPartialDetails %}
                                    <li data-id="{{agent.id}}">
                                        {% if agent.smallThumbnail != null %}
					  						<img src="{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('') ~ agent.smallThumbnail }}"/>
                                        {% else %}
                                            <img src="{{ asset(default_agent_image_path) }}" alt=""/>
                                        {% endif %}
                                        {{agent.name}}
                                    </li>
                                {% endfor %}
                                <li class="uv-no-results" style="display: none;">
                                    {{ 'No result found'|trans }}
                                </li>
                            </ul>
                        </div>
                        <div class="uv-filtered-tags">
                            {% if group %}
                                {% for user in user_service.getUsersByGroupId(group.id) %}
                                    <a class="uv-btn-small default" href="#" data-id="{{ user.id }}">
                                        {{ user.name }}
                                        <span class="uv-icon-remove"></span>
                                    </a>
                                {% endfor %}
                            {% endif %}
                        </div>
					</div>
				</div>
				<!-- //Field -->

                <!-- Field -->
				<div class="uv-element-block">
					<label class="uv-field-label">{{ 'Teams'|trans }}</label>
					<div class="uv-field-block" id="team-filter">
						<input type="hidden" name="tempTeams" class="uv-field" value="" />
                        <input class="uv-field uv-dropdown-other preloaded" type="text" id="team-filter-input">
                        <div class="uv-dropdown-list uv-bottom-left">
                            <div class="uv-dropdown-container">
                                <label>{{ 'Filter With'|trans }}</label>
                                <ul class="">
                                    {% for team in user_service.getSupportTeams() %}
                                        <li data-id="{{team.id}}">
                                            {{team.name}}
                                        </li>
                                    {% endfor %}
                                    <li class="uv-no-results" style="display: none;">
                                        {{ 'No result found'|trans }}
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="uv-filtered-tags">
                            {% if group %}
                                {% for team in group.getSupportTeams() %}
									{% if team.isActive %}
										<a class="uv-btn-small default" href="#" data-id="{{team.id }}">
											{{ team.name }}
											<span class="uv-icon-remove"></span>
										</a>
									{% endif %}
                                {% endfor %}
                            {% endif %}
                        </div>
					</div>
				</div>
				<!-- //Field -->

				<!-- Field -->
                <div class="uv-element-block">
					<label class="uv-field-label">{{ 'Group Status'|trans }}</label>
					<div class="uv-element-block">
						<label>
							<div class="uv-checkbox">
								<input type="checkbox" name="isActive" {{ group and group.isActive ? 'checked' : '' }}>
								<span class="uv-checkbox-view"></span>
							</div>
							<span class="uv-checkbox-label">{{ 'Group is Active'|trans }}</span>
						</label>
					</div>
                </div>
				<!-- //Field -->

				<!--CTA-->
				<input class="uv-btn" href="#" value="{{ 'Save Changes'|trans }}" type="submit">
				<!--//CTA-->
			</form>
			<!--//Form-->
		</div>
	</div>
{% endblock %}
{% block footer %}
	{{ parent() }}
	<script type="text/javascript">
		$(function () {
			var GroupModel = Backbone.Model.extend({
				validation: {
					'name': [{
                        required: true,
                        msg: "{{ 'This field is mandatory'|trans }}"
                    },{
                        pattern: /^((?![!@#$%^&*()<_+]).)*$/,
                        msg: "{{ 'This field must have characters only'|trans }}"
                    },{
						maxLength:50,
                        msg: "{{ 'Maximum character length is 50'|trans }}"
					}],
					'description': {
						required: true,
						msg: "{{ 'This field is mandatory'|trans }}"
					}
				}
			});
			var GroupForm = Backbone.View.extend({
				events : {
					'click .uv-btn': "saveGroup",
					'blur input, textarea': 'formChanged',
                    'click .uv-dropdown-list li': 'addEntity',
                    'click .uv-filtered-tags .uv-btn-small': 'removeEntity'
				},
				initialize : function() {
					Backbone.Validation.bind(this);
                    this.setAddedIds('#agent-filter')
                    this.setAddedIds('#team-filter')
					var jsonContext = JSON.parse('{{ errors|raw }}');
		    		for (var field in jsonContext) {
		    			Backbone.Validation.callbacks.invalid(this, field, jsonContext[field], 'input');
					}
				},
				formChanged: function(e) {
			    	this.model.set(Backbone.$(e.currentTarget).attr('name'), Backbone.$(e.currentTarget).val())
			    	this.model.isValid([Backbone.$(e.currentTarget).attr('name')])
			    },
				saveGroup : function (e) {
					e.preventDefault();
			        this.model.set(this.$el.serializeObject());
			        if(this.model.isValid(true)) {
						this.$el.find('.uv-btn').attr('disabled', 'disabled');
			            this.$el.submit();
			        }
				},
                setAddedIds: function(selector) {
                    var ids = [];
                    $(selector).find('.uv-filtered-tags .uv-btn-small').each(function() {
                        ids.push($(this).attr('data-id'))
                    });

                    $(selector).find("input[type='hidden']").val(ids.join(','))
                },
                addEntity: function(e) {
                    currentElement = Backbone.$(e.currentTarget);
                    if(id = currentElement.attr("data-id")) {
                        parent = currentElement.parents(".uv-field-block");
                        parent.find('input').val('')
                        parent.find("li:not(.uv-no-results)").show()
                        if(!parent.find(".uv-filtered-tags a[data-id='" + id + "']").length) {
                            parent.find('.uv-filtered-tags').append("<a class='uv-btn-small default' href='#' data-id='" + id + "'>"+currentElement.text()+"<span class='uv-icon-remove'></span></a>")
                            this.setAddedIds("#" + parent.attr('id'))
                        }
                    }
                },
                removeEntity: function(e) {
                    var parent = Backbone.$(e.currentTarget).parents(".uv-field-block")
                    Backbone.$(e.currentTarget).remove()
                    this.setAddedIds("#" + parent.attr('id'))
                }
			});

			groupForm = new GroupForm({
				el : $("#group-form"),
				model : new GroupModel()
			});	
		});
	</script>
{% endblock %}
