<!DOCTYPE html>
<html>
<head>
	<title>Kiosk</title>
	{% load static %}
	{% load custom_tags_and_filters %}

	{# jQuery #}
	<script type="text/javascript" src="{% static "jquery.js" %}"></script>

	{# Bootstrap #}
	<script type="text/javascript" src="{% static "bootstrap/js/bootstrap.js" %}"></script>
	<link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap.css" %}"/>
	<link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap-theme.css" %}"/>

	{# Numpad #}
	<script type="text/javascript" src="{% static "numpad/custom_numpad.jquery.js" %}"></script>
	<link rel="stylesheet" type="text/css" href="{% static "numpad/numpad.jquery.css" %}"/>

	{# Virtual Keyboard	#}
	<script type="text/javascript" src="{% static "virtualkeyboard/jquery.keyboard.min.js" %}"></script>
	<link rel="stylesheet" type="text/css" href="{% static "virtualkeyboard/keyboard-basic.min.css" %}"/>

	{# NEMO #}
	<script type="text/javascript" src="{% static "nemo.js" %}"></script>
	<link rel="stylesheet" type="text/css" href="{% static "nemo.css" %}"/>

	{# Kiosk #}
	<link rel="stylesheet" type="text/css" href="{% static "kiosk/kiosk.css" %}"/>

	{# Badge Reader #}
	<script type="text/javascript" src="{% static "badge_reader.js" %}"></script>

	<!--suppress CssUnusedSymbol -->
	<style>
		.btn-extra-large
		{
			margin-top: 50px;
			margin-bottom: 50px;
			font-size: 36px;
		}
	</style>
</head>
<body>
	<div id="kiosk-container">
		<div class="container-fluid">
			<div id="default_content">
				<h1>Scan your badge to control tools</h1>
				<div id="occupancy"></div>
			</div>
			<div id="error" style="display: none"><h1>There was a problem communicating with the web server. Please visit the user office for assistance.</h1></div>
            <div id="interlock_error" style="display: none">
                <h1 class="text-center">
                    <span style="font-size: xx-large;margin-right:10px;" class="glyphicon glyphicon-exclamation-sign danger-highlight"></span>
                    Interlock error
                </h1>
                <h3 id="interlock_message" class="text-center"></h3>

                <div class="col-xs-4" style="margin: 40px auto; float: initial">
                    <div id="inter_bypass" class="btn-block" style="display: none; margin-bottom: 10px">
                        <div class="alert alert-success" style="text-align:center; margin-bottom:0">
                            <span id="bypass_text" style="font-size:x-large"></span>
                        </div>
                    </div>
                    <div id="inter_try_again" class="btn-block" style="margin-bottom: 10px">
                        <div class="alert alert-info" style="text-align:center; margin-bottom:0">
                            <span style="font-size:x-large">Try again</span>
                        </div>
                    </div>
                    <div id="inter_back" class="btn-block" style="margin-bottom: 10px">
                        <div class="alert alert-warning" style="text-align:center; margin-bottom:0; font-size:x-large">
                            Go back
                        </div>
                    </div>
                    <div class="btn-block" onclick="revert()">
                        <div class="alert alert-warning" style="text-align:center; margin-bottom:0">
                            <span style="font-size:x-large">I've finished using this kiosk</span>
                        </div>
                    </div>
                </div>
            </div>
			<div id="status" style="display: none"></div>
			<div><h1 style="color:lightgrey" id="badge_number"></h1></div>
		</div>
		<div id="countdown" style="position: fixed; bottom: 0; right: 0;font-size: x-large"></div>
	</div>
	{% include 'base/footer.html' %}
	<script type="text/javascript">
		let kiosk_badge_reader = new BadgeReader(send_badge_number, "{{ badge_reader.send_key }}" {% if badge_reader.record_key %}, "{{ badge_reader.record_key }}"{% endif %});
		let timeout_handle = null;
		let countdown_handle = null;
		let occupancy = new URLSearchParams(window.location.search).get('occupancy');

		let default_content_element = $("#default_content");
		let status_element = $("#status");
		let error_element = $("#error");
		let error_interlock_element = $("#interlock_error");
		let bypass_button = $("#inter_bypass");

        function show_alerts()
        {
            let alert_users = $(".alert.show-on-load");
            alert_users.each(function(index, element) {
                let speed = 4500;
                if ($(element).data('speed')) speed = $(element).data('speed')
                $(element).fadeTo(speed, 500).slideUp(500, function () {
                    $(element).slideUp(500);
                });
            });
        }
		function send_badge_number(badge_number)
		{
			clear_timeout();
			load_choices(badge_number);
		}

		if(occupancy)
		{
			fetch_occupancy();
			set_interval_when_visible(document, fetch_occupancy, 30000);
		}

		function load_complete(response, status, xml_http_request)
		{
			if(status === "error")
			{
				default_content_element.hide();
				status_element.hide();
				error_interlock_element.hide();
				error_element.show();
				revert(15);
			}
			$("#badge_number").html("");
			show_alerts();
		}
		function revert(delay)
		{
			clear_timeout();
			let countdown = delay;
			delay = delay * 1000;
			timeout_handle = setTimeout(revert_to_default_content, delay);
			countdown_handle = setInterval(function()
            {
				$('#countdown').html(countdown);
				countdown --;
			}, 1000);
		}
		function revert_to_default_content()
		{
			fetch_occupancy();
			clear_timeout();
			close_numpads();
			close_keyboards();
			status_element.hide();
			error_interlock_element.hide();
			error_element.hide();
			$("#badge_number").html("");
			default_content_element.show();
		}
		function clear_timeout()
		{
			if(timeout_handle != null)
				clearTimeout(timeout_handle);
			timeout_handle = null;
			if (countdown_handle != null)
				clearInterval(countdown_handle);
			countdown_handle = null;
			$("#countdown").html("");
		}
		function select_project(element, project_id)
		{
			$(".project-choice").removeClass('active');
			$(element).addClass('active');
			$("#project_id").val(project_id);
			$("#start_reserve").show();
		}
		function load_choices(badge_number)
		{
			let data = {
				'location': '{{ location }}',
				'badge_number': badge_number
			};
			default_content_element.hide();
			error_interlock_element.hide();
			error_element.hide();
			status_element.html("<h1>Loading choices...</h1>").show().load('{% url 'kiosk_choices' %}?' + $.param(data), undefined, load_complete);
		}
		function tool_information(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			status_element.html("<h1>Loading tool information...</h1>").show().load(url, undefined, load_complete);
		}
		function view_category(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			status_element.html("<h1>Loading category...</h1>").show().load(url, undefined, load_complete);
		}
		function tool_reservation(url)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = serialize('#tool_control');
			status_element.html("<h1>Loading tool reservation...</h1>").show().load(url, data, load_complete);
		}
		function cancel_reservation(url, reservation_id)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
            let data = serialize('#cancel_reservation_' + reservation_id);
			status_element.html("<h1>Cancelling reservation...</h1>").show().load(url, data, load_complete);
		}
		function reserve_tool()
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = serialize('#tool_reservation');
			status_element.html("<h1>Reserving tool...</h1>").show().load('{% url 'reserve_tool_from_kiosk' %}', data, load_complete);
		}
		function try_post_catch_interlock_error(url, data)
        {
            ajax_post(url, data, function(response, status, xml_http_request) {interlock_success_callback(response, status, xml_http_request)}, function(response, status, xml_http_request) { return interlock_failure_callback(response, status, xml_http_request, url, data) })
        }
		function enable_tool(tool_id)
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = serialize('#tool_control');
			if (tool_id)
			{
				data['tool_id'] = tool_id;
			}
			status_element.html("<h1>Enabling tool...</h1>").show();
			try_post_catch_interlock_error('{% url 'enable_tool_from_kiosk' %}', data);
		}
		function disable_tool()
		{
			default_content_element.hide();
			error_element.hide();
			error_interlock_element.hide();
			let data = serialize('#tool_control');
			status_element.html("<h1>Disabling tool...</h1>").show();
			try_post_catch_interlock_error('{% url 'disable_tool_from_kiosk' %}', data);
		}
		function interlock_success_callback(response, status, xml_http_request)
        {
            error_interlock_element.hide();
            status_element.html(response).show();
        }
		function interlock_failure_callback(response, status, xml_http_request, url, data)
        {
            revert(45);
            {# Specific case here where we have an error but it could be bypassed #}
            if (status === 'error' && response.status === 501)
            {
                status_element.hide();
                let response_data = response.responseJSON;
                $("#interlock_message").html(response_data['message'])
                bypass_button.hide();
                error_interlock_element.show();
                {# we can bypass, show the button #}
                if (response_data["bypass_allowed"] === true)
                {
                    bypass_button.off("click")
                    $('#bypass_text').html(response_data['action'] + " anyway");
                    bypass_button.show();
                    bypass_button.one('click', function ()
                    {
                        data["bypass"] = 'True';
                        try_post_catch_interlock_error(url, data);
                    });
                }
                {# hook up try again button #}
                let inter_try_again_button = $("#inter_try_again");
                inter_try_again_button.off("click");
                inter_try_again_button.one('click', function ()
                {
                    error_interlock_element.hide();
                    status_element.html("<h1>Trying again...</h1>").show();
                    setTimeout(function()
                    {
                        try_post_catch_interlock_error(url, data);
                    }, 200);
                });
                {# hook up back button #}
                let inter_back_button = $("#inter_back");
                inter_back_button.off("click");
                inter_back_button.one('click', function ()
                {
                    tool_information("{% url 'kiosk_tool_information' '11111111111' '999999999999' 'back_to_start' %}".replace('11111111111', data.tool_id).replace('999999999999', data.customer_id).replace('back_to_start', data.back));
                });
            }
            else
            {
                load_complete(response, status, xml_http_request);
            }
        }
		function csrf_token()
		{
			return '{{ csrf_token }}';
		}
		function fetch_occupancy()
		{
			ajax_get('{% url 'kiosk_occupancy' %}', {'occupancy': occupancy}, function(response) { $("#occupancy").html(response); });
		}
		function close_numpads()
		{
			$.each($('[data-numpad]'), function (index, item)
            {
				$(item).data('numpad').close(false);
			});
		}
        function close_keyboards()
		{
            $.each($('.ui-keyboard-input'), function (index, item)
			{
                $(item).data('keyboard').close(false);
            })
        }
	</script>
</body>
</html>