{% extends 'base_narrow.html' %}

{% block body %}
<div class="col-12">
	<h2 class="text-center">{{_('Logout')}}</h2>
</div>

<div class="col-12">
	<noscript>
		<div class="alert alert-warning" role="alert">{{_('Javascript is required for automatic logout')}}</div>
	</noscript>
	<p>{{_('While you successfully logged out of the Single-Sign-On service, you may still be logged in on these services:')}}</p>
	<ul>
	{% for client in clients if client.logout_urls %}
		<li class="client" data-urls='{{ client.logout_urls|tojson }}'>
			{{ client.client_id }}
			<span class="status-active spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
			<i class="status-success fas fa-check d-none"></i>
			<i class="status-failed fas fa-exclamation d-none"></i>
		</li>
	{% endfor %}
	</ul>

	<p>
		{{_('Please wait until you have been automatically logged out of all services or make sure of this yourself.')}}
	</p>

	<button id="retry-button" class="btn btn-block btn-primary d-none" disabled>
		<span id="cont-text">{{_('Logging you out on all services ...')}}</span>
	</button>

	<a href="{{ request.values.get('ref') or '/' }}" class="btn btn-block btn-secondary">
		<span>{{_('Skip this and continue')}}</span>
	</a>

</div>

<script>
function logout_services() {
	$("#retry-button").prop('disabled', true);
	let all_promises = [];
	$("li.client").each(function () {
		let elem = $(this);
		let p = new Promise(function (resolve, reject) {
			elem.find('.status-active').removeClass('d-none');
			elem.find('.status-success').addClass('d-none');
			elem.find('.status-failed').addClass('d-none');
			resolve();
		});
		elem.data('urls').forEach(function (url) {
			p = p.then(function () {
				return fetch(url[1], {method: url[0], credentials: 'include', mode: 'no-cors'});
			});
		});
		p = p.then(function () {
			console.log('done', elem);
			elem.find('.status-active').addClass('d-none');
			elem.find('.status-success').removeClass('d-none');
			elem.removeClass('client');
		})
		.catch(function (err) {
			elem.find('.status-active').addClass('d-none');
			elem.find('.status-failed').removeClass('d-none');
			console.log(err);
			throw err;
		});
		all_promises.push(p);
	});
	Promise.allSettled(all_promises).then(function (results) {
		console.log(results);
		for (result of results) {
			if (result.status == 'rejected')
				throw result.reason;
		}
		$('#cont-text').text({{_('Done, redirecting ...')|tojson}});
		window.location = {{ (request.values.get('ref') or '/')|tojson }};
	}).catch(function (err) {
		$("#retry-button").prop('disabled', false);
		$('#cont-text').text({{_('Log out failed on some services. Retry?')|tojson}});
	});
}

$("#retry-button").removeClass('d-none');
$("#retry-button").on('click', logout_services);
logout_services();
</script>
{% endblock %}
