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

{% block title %}API Access Tokens{% endblock %}

{% block pageContent %}
	<style>
		.uv-inner-section .uv-action-bar {
			border-bottom: unset;
			padding: unset;
		}

		.api-settings-collection {
			margin: 10px 20px 0px 0px;
		}

		.api-settings-collection .uv-splash {
			text-align: center;
			margin: unset;
			border-top: 1px solid #ddd;
			padding-top: 40px;
		}

		.api-settings-collection .uv-splash .uv-splash-image {
			margin-top: 50px;
		}

		.api-settings-collection .uv-api-credentials-collection-item {
			padding: 20px 0px;
			border-bottom: 1px dashed #ccc;
		}

		.api-settings-collection p:first-child {
			color: #757575;
			font-size: 15px;
			line-height: 1.4em;
			padding-bottom: 20px;
			border-bottom: 1px dashed #ccc;
			margin: unset;
		}

		.uv-api-credentials-collection-item ul {
			padding: unset;
			list-style: none;
			margin: 0px 0px 20px 0px;
		}

		.uv-api-credentials-collection-item ul li {
			font-size: 15px;
			line-height: 1.4em;
			margin-bottom: 4px;
		}

		.uv-api-credentials-collection-item ul li label {
			color: #545454;
			font-weight: 700;
			width: 140px;
			display: inline-block;
		}

		.uv-api-credentials-collection-item input[type="text"] {
			display: block;
			color: #6F6F6F;
			font-size: 14px;
			font-weight: 700;
			line-height: 1.4em;
			letter-spacing: 1px;
			text-overflow: ellipsis;
			width: 512px;
			padding: 8px 10px 6px;
			background: #FAFAFA;
			border: dashed 1px #B1B1AE;
			border-radius: 4px;
			transition: 0.2s cubic-bezier(0.4, 0, 0.2, 1);
		}

		.uv-api-credentials-collection-item .uv-settings-buttons {
			margin: 20px 0px 0px;
		}

		.uv-api-credentials-collection-item .uv-settings-buttons button {
			margin: unset;
		}
	</style>

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

		{{ 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 %}">
            <div class="uv-action-bar">
                <div class="uv-action-bar-col-lt" style="vertical-align: middle;">
					<h1>API Access Tokens</h1>
                </div>

				<div class="uv-action-bar-col-rt" style="vertical-align: middle;">
					<a href="{{ path('uvdesk_api_create_configuration') }}" type="button" class="uv-btn-action" style="margin: unset;">+ Access Credentials</a>
				</div>
            </div>

            <div id="api-settings-collection" class="api-settings-collection"></div>
		</div>
    </div>
{% endblock %}

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

    <script type="text/template" id="no-settings-template">
		<div class="uv-splash">
			<img class="uv-splash-image" src="{{ asset('bundles/uvdeskcoreframework/images/splash/onboarding.png') }}" alt="Api Settings">
			<p>Create api access credentials to easily communicate with the uvdesk api now!</p>
		</div>
	</script>

    <script id="access-credential-item-template" type="text/template">
		<div id="token-<%- id %>">
			<ul>
				<li><label>Name:</label> <span><%- name %><span></li>

				<% if (isEnabled) { %>
					<li><label>Status:</label> <span style="color: #2ED04C;">Enabled</span></li>
				<% } else { %>
					<li><label>Status:</label> <span style="color: #FF5656;">Disabled</span></li>
				<% } %>
				
				<li><label>Date Created:</label> <%- dateCreated %></li>
			</ul>
			
			<div class="uv-element-block" style="margin: unset;">
				<input type="text" class="uv-api-token-input" value="<%- token %>" readonly >
			</div>

			<div class="uv-settings-buttons">
				<% if (isEnabled) { %>
					<button type="button" class="uv-btn-small disable-configuration" style="background: #FF5656;">Disable</button>
				<% } else { %>
					<button type="button" class="uv-btn-small enable-configuration" style="background: #2ED04C;">Enable</button>
				<% } %>

				<button type="button" class="uv-btn-small delete-configuration" style="background: #FF5656;">Delete Credentials</button>
				<button type="button" class="uv-btn-small configuration-copy-clipboard" data-ref="<%- id %>">Copy Access Token</button>
			</div>
		</div>
    </script>

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

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

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

			var ConfigurationCollection = AppCollection.extend({
				model: ConfigurationModel,
				url: "{{ path('uvdesk_api_load_configurations_xhr') }}",
				filterParameters : {
					"isActive" : "",
					"search" : ""
				},
				parseRecords: function (resp, options) {
					return resp.types;
				},
				initialize: function() {
					this.syncData();
				},
				syncData: function() {
					app.appView.showLoader();

					this.fetch({
						reset: true,
						data: this.getValidParameters(),
						success: function(model,response) {
							app.appView.hideLoader();
							var configurationListView = new ConfigurationList(response);

							if (globalMessageResponse) {
								app.appView.renderResponseAlert(globalMessageResponse);
							}

							globalMessageResponse = null;
						},
						error: function (model, xhr, options) {
							if (url = xhr.getResponseHeader('Location')) {
								window.location = url;
							}
						}
					});
				}
			});

			var ConfigurationView = Backbone.View.extend({
				tagName: "div",
				className: "uv-api-credentials-collection-item",
				template: _.template($("#access-credential-item-template").html()),
				events: {
					'click .enable-configuration' : "enableConfiguration",
					'click .disable-configuration' : "disableConfiguration",
					'click .delete-configuration' : "confirmRemove",
					'click .configuration-copy-clipboard' : "copyTokenToClipboard"
				},
				render: function() {
					this.$el.html(this.template(this.model));
					return this;
				},
				confirmRemove: function(e) {
					e.preventDefault();
					app.appView.openConfirmModal(this)
				},
				removeItem: function (e) {
					app.appView.showLoader();

					$.ajax({
						url: "{{ path('uvdesk_api_update_configuration_xhr') }}/" + this.model.id,
						data: this.model,
						type: 'DELETE',
						success: function (response) {
							app.appView.hideLoader();
							globalMessageResponse = response;

							configurationCollection.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);
						}
					});
				},
				enableConfiguration: function (ev) {
					this.model.isEnabled = true;

					console.log(this.model);

					app.appView.showLoader();

					$.ajax({
						url: "{{ path('uvdesk_api_update_configuration_xhr') }}/" + this.model.id,
						data: this.model,
						type: 'PATCH',
						success: function (response) {
							app.appView.hideLoader();
							globalMessageResponse = response;
							
							configurationCollection.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);
						}
					});
				},
				disableConfiguration: function (ev) {
					this.model.isEnabled = false;

					app.appView.showLoader();

					$.ajax({
						url: "{{ path('uvdesk_api_update_configuration_xhr') }}/" + this.model.id,
						data: this.model,
						type: 'PATCH',
						success: function (response) {
							app.appView.hideLoader();
							globalMessageResponse = response;
							
							configurationCollection.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);
						}
					});
				},
				copyTokenToClipboard: function (ev) {
					let targetId = 'token-' + $(ev.currentTarget).data('ref');
					let el = $('#' + targetId + ' .uv-api-token-input');
					el.select();
					document.execCommand("copy");
					console.log('copying token', el.val());
				}
			});

			var ConfigurationList = Backbone.View.extend({
				el: $(".api-settings-collection"),
				template: _.template($("#no-settings-template").html()),
				initialize : function(listItems) {
					this.render(listItems);
				},
				render : function (items) {
					this.$el.empty();
					
					if (items.length > 0) {
						this.$el.append('<p>Manage your uvdesk api access credentials below:</p>');
						_.each(items, function (item) {
							this.renderType(item);
						}, this);
					} else {
						this.$el.html(this.template());
					}
				},
				renderType : function (item) {
					var configuration = new ConfigurationView({
						model: item
					});

					this.$el.append(configuration.render().el);
				}
			});

			var configurationCollection = new ConfigurationCollection();
		});
	</script>
{% endblock %}