<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{{ layout_name }}</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            html, body {
                background-color: gray;
				width: 100%;
                height: 100%;
            }

			.item {
				display: inline-block;
				*display: inline;
				zoom: 1;
				width: 81
			}
        </style>
		<script type="text/javascript" src="/jquery-1.9.1.min.js"></script>
    </head>
	<script type="text/javascript">
	// Input
	var DOOR_OPENED = 0;
	var DOOR_CLOSED = 1;

	// Output state
	var BUTTON_OPEN = 0;
	var BUTTON_CLOSE = 1;

	// Button enable state
	var BUTTON_ENABLED = 1;
	var BUTTON_DISABLED = 0;

	// Commands
	var COMMAND_OPEN = 1;
	var COMMAND_CLOSE = 0;

	// Modes
	{% set MODE_ON = 0 %}
	{% set MODE_OFF = 1 %}
	{% set MODE_CLOSE = 2 %}

	// NONC
	var NORMAL_OPEN = 1;
	var NORMAL_CLOSE = 0;

	// Request
	var REQUEST_TIMEOUT = 2000;

	// Doors' state (Opened or closed)
	var doorsState = {{ inputs_map | safe }};

	// Buttons' current state (Open or Close button)
	var buttonsState = {{ outputs_map | safe }};

	// Buttons enable state (Enabled or disabled)
	var buttonsEnableState = {{ outputs_map | safe }};

	// Delay before close the door
	var delaysMap = {{ delays_map | safe }};

	// NC/NO map
	var noncMap = {{ nonc_map | safe }};

	function updateDoorState(inPin) {
		var state = doorsState[inPin];
		var stateStr = (state == DOOR_OPENED) ? 'opened' : 'closed';
		var url = '/images/door.' + stateStr + '.png';
		$('#door-' + inPin).attr('src', url);
	}

	function updateButtonState(outPin) {
		var enabled = buttonsEnableState[outPin];
		var state = buttonsState[outPin];

    {% if mode == MODE_CLOSE %}
      var stateStr = 'close';
    {% else %}
		  var stateStr = (state == BUTTON_OPEN) ? 'open' : 'close';
    {% endif %}

		{% if mode == MODE_CLOSE %}
			var grayed = (state == BUTTON_OPEN) ? '.gray' : (enabled ? '' : '.gray');
		{% else %}
			var grayed = enabled ? '' : '.gray';
		{% endif %}

		var url = '/images/' + stateStr + grayed + '.png';

		$('#btn-' + outPin).attr('src', url);

		// buttonsEnableState[outPin] = enabled ? BUTTON_ENABLED : BUTTON_DISABLED;
	}

    function handleButtonClick(outPin) {
		if (buttonsEnableState[outPin] == BUTTON_DISABLED) return;
		var cmd = (buttonsState[outPin] == BUTTON_OPEN) ? COMMAND_OPEN : COMMAND_CLOSE;

		{% if mode == MODE_CLOSE %}
			if (cmd == COMMAND_OPEN) return;
		{% endif %}

		var url = "/{{ layout_id }}?outputs=" + outPin + ',' + cmd;
		$.get(url, function(resp) {
			console.log(resp);
		});

		var cmdStr = (cmd == COMMAND_OPEN) ? 'COMMAND_OPEN' : 'COMMAND_CLOSE';
		console.log(cmdStr + ' sent to outPin ' + outPin);

		buttonsEnableState[outPin] = false;
		updateButtonState(outPin);

		if (cmd == COMMAND_OPEN) {
			if (delaysMap[outPin] > 0) {
				console.log('Queued command to active button ' + outPin + ' automatically in ' + delaysMap[outPin] + ' secs');
				setTimeout(function() {
					buttonsState[outPin] = BUTTON_CLOSE;
					handleButtonClick(outPin);
				}, delaysMap[outPin] * 1000);
			}
		}
    }

	function request() {
		$.get('/read?layout={{ layout_id }}', function(data) {
			if (data.charAt(0) != '{') return;
			var resp = $.parseJSON(data);

			console.log(resp);

			var i;
			// Process inputs (doors)
			for (i in doorsState) {
				if (typeof resp.inp[i] === 'undefined') continue;

				var pin = i;
				var input = resp.inp[pin];
				var state = resp.state[pin];
				var nonc = noncMap[pin];

				// Ignore 2rd row on alarm page
				if (state != nonc) {
					if (input === 0) input = 1;
					else input = 0;
				}

				// Hereby input is final input
				doorsState[pin] = input;
				updateDoorState(pin);
			}

			for (i in buttonsState) {
				if (typeof resp.out[i] === 'undefined') continue;
				var pin = i;
				var output = resp.out[pin];

				buttonsState[pin] = output;
				buttonsEnableState[pin] = BUTTON_ENABLED;
				updateButtonState(pin);
			}
		});

		setTimeout(request, REQUEST_TIMEOUT);
	}

	function init() {
		var i;

		// All doors closed as initial state
		for (i in doorsState) {
			doorsState[i] = DOOR_CLOSED;
		}

		// All buttons are open button as initial state
		for (i in buttonsState) {
			buttonsState[i] = BUTTON_OPEN;
		}

		// But all disabled
		for (i in buttonsEnableState) {
			buttonsEnableState[i] = BUTTON_DISABLED;
		}

		if (typeof window.console === 'undefined') {
			window.console = {
				log: function(str) {
				}
			}
		}

		$(document).ready(function() {
			var i;

			for (i in doorsState) {
				updateDoorState(i);
			}

			for (i in buttonsEnableState) {
				updateButtonState(i);

				// Add click event
				(function(btn) {
					$('#btn-' + btn).click(function() {
						handleButtonClick(btn);
					});
				})(i);
			}

			request();
		});
	}

	init();
    </script>
    <body>
        <table style="width:100%">
			<tr>
				{% for name in door_names %}
					<td align="center">
						<font color="#ffffff">{{ name }}</font>
					</td>
				{% endfor %}
			</tr>
			<tr>
				{% for door in input_pins %}
					<td align="center">
						<img id="door-{{ door }}" src="/images/door.opened.png" />
					</td>
				{% endfor %}
			</tr>
			<tr>
				{% if mode != MODE_OFF %}
					{% for button in output_pins %}
						<td align="center">
							<img id="btn-{{ button }}" src="/images/close.png" />
						</td>
					{% endfor %}
				{% endif %}
			</tr>
        </table>
    </body>
</html>
