<!DOCTYPE html>
<html style="height: 100%;">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width">
		<title>ASR tangibles</title>

		<style>
			body {
				width: 100%;
				height: 100%;
				margin: 0;
				background-color: #EEEEEE;
			}
			#box {
				width: 100%;
				height: 100%;
			}
			.tuioCursor {
				background: #111;
				height: 8px;
				left: 0;
				position: absolute;
				top: 0;
				width: 8px;
			}
			.tuioObj {
				background: #111;
				height: 15px;
				left: 0;
				position: absolute;
				top: 0;
				width: 8px;
				rotate: 0deg;
			}
		</style>
	</head>

	<body>

		<!--<div id="box"></div>-->
		<canvas id="box"></canvas>

		<!--<script src="/jquery-1.7.2.js"></script>-->
		<script src="/lodash.js"></script>
		<script src="/socket.io/socket.io.js"></script>
		<script src="/tuio.js"></script>
		<script>
			let config = {};
			const getConfig = () => {
				return fetch('/config.json');
			};

			getConfig().then(response => {
				return response.json();
			}).then(data => {
				config = data;

				const urlParams = new URLSearchParams(window.location.search);
				const sectionParam = urlParams.get('section');
				const section = sectionParam ? parseInt(sectionParam, 10) : 100;

				if (config.app.debug) {
					console.log('### Frontend debug activated ###');
				}

				const screenW = window.innerWidth;
				const screenH = window.innerHeight;

				if (config.app.debug && config.app.debugLog.frontend.emitter.screen) {
					console.log(`-- Screen width: ${screenW} --`);
					console.log(`-- Screen height: ${screenH} --`);
				}

				/* -------
				 * EMITTER
				 * -------
				 */
				const box = document.getElementById('box');

				const eventHandler = (evt, type) => {
					const touches = [];
					for (var i = 0; i < evt.changedTouches.length; i++) {
						touches[i] = {
							clientX: evt.changedTouches[i].clientX,
							clientY: evt.changedTouches[i].clientY,
							force: evt.changedTouches[i].force,
							identifier: ((evt.changedTouches[i].identifier + 1) % 100) + section,
							pageX: evt.changedTouches[i].pageX,
							pageY: evt.changedTouches[i].pageY,
							radiusX: evt.changedTouches[i].radiusX,
							radiusY: evt.changedTouches[i].radiusY,
							rotationAngle: evt.changedTouches[i].rotationAngle,
							screenX: evt.changedTouches[i].screenX,
							screenY: evt.changedTouches[i].screenY
						};
					};

					if (config.app.debug && config.app.debugLog.frontend.emitter.events) {
						console.log(`-- Event: ${type} --`, touches);
					}

					if (config.app.debug && config.app.debugDisplay) {
						box.innerHTML = evt.touches.length;
					}

					fetch(`http://localhost:${config.app.httpPort}/emitter/json`, {
						method: 'POST',
						mode: 'cors',
						cache: 'no-cache',
						credentials: 'same-origin',
						headers: {
							'Content-Type': 'application/json'
						},
						redirect: 'follow',
						referrerPolicy: 'no-referrer',
						body: JSON.stringify({
							type,
							section,
							screenW,
							screenH,
							touches
						})
					});
					evt.preventDefault();
				};

				box.addEventListener('touchstart', (evt) => {
					return eventHandler(evt, 'touchstart');
				});

				box.addEventListener('touchmove', (evt) => {
					return eventHandler(evt, 'touchmove');
				});

				box.addEventListener('touchend', (evt) => {
					return eventHandler(evt, 'touchend');
				});

				/* --------
				 * RECEIVER
				 * --------
				 */

				const canvas = document.getElementById('box');
				canvas.width = screenW;
				canvas.height = screenH;
				context = canvas.getContext('2d');

				const drawTriangle = (a, b, c) => {
					context.clearRect(0, 0, canvas.width, canvas.height);
					const path = new Path2D();
					path.moveTo(Math.round(a.x), Math.round(a.y));
					path.lineTo(Math.round(b.x), Math.round(b.y));
					path.lineTo(Math.round(c.x), Math.round(c.y));
					context.fill(path);
				};
				const client = new Tuio.Client({
					host: `http://localhost:${config.app.httpPort}`
				});

				const cursors = {};
				const objects = {};

				onConnect = function() {
					if (config.app.debug) {
						console.log('connected to web-socket');
					}
				},

				onAddTuioCursor = function(addCursor) {
					/*
					var $addCursor = $('<div class="tuioCursor"></div>');
					$('body').append($addCursor);
					cursors[addCursor.getCursorId()] = $addCursor;
					*/
					onUpdateTuioCursor(addCursor);
					if (config.app.debug && config.app.debugLog.frontend.receiver.onAddTuioCursor) {
						console.log('addTuioCursor', addCursor);
					}
				},

				onUpdateTuioCursor = function(updateCursor) {
					/*
					var $updateCursor = cursors[updateCursor.getCursorId()];
					$updateCursor.css({
						left: updateCursor.getScreenX(screenW),
						top: updateCursor.getScreenY(screenH)
					});
					*/
					if (config.app.debug && config.app.debugLog.frontend.receiver.onUpdateTuioCursor) {
						console.log('updateTuioCursor', updateCursor);
					}
				},

				onRemoveTuioCursor = function(removeCursor) {
					/*
					var $removeCursor = cursors[removeCursor.getCursorId()];
					$removeCursor.remove();
					delete[removeCursor.getCursorId()];
					*/
					if (config.app.debug && config.app.debugLog.frontend.receiver.onRemoveTuioCursor) {
						console.log('removeTuioCursor', removeCursor);
					}
				},

				onAddTuioObject = function(addObject) {
					/*
					var $addObject = $('<div class="tuioObj"></div>');
					$('body').append($addObject);
					objects[addObject.symbolID] = $addObject;
					*/

					onUpdateTuioObject(addObject);
					if (config.app.debug && config.app.debugLog.frontend.receiver.onAddTuioObject) {
						console.log('addTuioObject', addObject);
					}
				},

				onUpdateTuioObject = function(updateObject) {
					/*
					var $updateObject = objects[updateObject.symbolID];
					$updateObject.css({
						left: updateObject.getScreenX(screenW),
						top: updateObject.getScreenY(screenH),
						rotate : updateObject.getAngleDegrees()
					});
					*/

					const apexAngle = 35;
					const mediatrice = 300;

					if (config.app.debugDisplay) {
						const x = updateObject.xPos;
						const y = updateObject.yPos;

						const apex = {
							x: Math.cos(updateObject.angle * Math.PI / 180) * (mediatrice / 2) + x,
							y: Math.sin(updateObject.angle * Math.PI / 180) * (mediatrice / 2) + y
						};
						const b = {
							x: Math.cos((apexAngle / 2) * Math.PI / 180) * (mediatrice / 2) + apex.x,
							y: Math.sin((apexAngle / 2) * Math.PI / 180) * (mediatrice / 2) + apex.y
						};
						const c = {
							x: Math.cos((-1 * apexAngle / 2) * Math.PI / 180) * (mediatrice / 2) + apex.x,
							y: Math.sin((-1 * apexAngle / 2) * Math.PI / 180) * (mediatrice / 2) + apex.y
						};
						drawTriangle(apex, b, c);
					}

					if (config.app.debug && config.app.debugLog.frontend.receiver.onUpdateTuioObject) {
						console.log('updateTuioObject', updateObject);
					}
				},

				onRemoveTuioObject = function(removeObject) {
					/*
					var $removeObject = objects[removeObject.symbolID];
					$removeObject.remove();
					delete[removeObject.symbolID];
					*/
					if (config.app.debug && config.app.debugLog.frontend.receiver.onRemoveTuioObject) {
						console.log('removeTuioObject', removeObject);
					}
				},

				onRefresh = function(time) {
					if (config.app.debug && config.app.debugLog.frontend.receiver.onRefresh) {
						console.log('refresh', time);
					}
				};

				client.on('connect', onConnect);
				client.on('addTuioCursor', onAddTuioCursor);
				client.on('updateTuioCursor', onUpdateTuioCursor);
				client.on('removeTuioCursor', onRemoveTuioCursor);
				client.on('addTuioObject', onAddTuioObject);
				client.on('updateTuioObject', onUpdateTuioObject);
				client.on('removeTuioObject', onRemoveTuioObject);
				client.on('refresh', onRefresh);
				client.connect();
			});
		</script>
	</body>
</html>