<style>
    .error {
        color: darkred;
    }
</style>
<script>
	import {router} from 'tinro';
	import {Html5QrcodeScanner} from "html5-qrcode";
	import {Html5Qrcode} from "html5-qrcode";
	import {useTracker} from "meteor/rdb:svelte-meteor-data";
	import {Meteor} from "meteor/meteor";
	import { Session } from 'meteor/session';

	let c = 0;

	$: deviceId = null;
	$: chromebookData = [];
	$: {
		if (deviceId) {
			Meteor.call("DataCollection.chromebookData", deviceId, (error, result) => {
				// console.log("Call returned");
				if (error) {
					console.error(error);
				} else {
					chromebookData = result;
					// console.log("result: " + result);
				}
			});
		}
		else {
			chromebookData = [];
		}
	}

	function fakeScan() {
		setTimeout(() => {
			let decodedText = "1e3e99ef-adf4-4aa2-8784-205bc60f0ce3";

			//deviceId = decodedText;
			//window.location.href="/chromebooks/byDevice/" + encodeURIComponent(decodedText);
			//router.location.goto("/chromebooks/byDevice/" + encodeURIComponent(decodedText));
			router.goto("/chromebooks?deviceId=" + encodeURIComponent(decodedText));
		}, 1000);
	}
	function clear() {
		deviceId = "";
	}

	function setDeviceId(id) {
		deviceId = id;
	}

	let html5QrCode;

	function scanner() {
		html5QrCode = new Html5Qrcode("reader");
		const config = {fps: 10, qrbox: {width: 250, height: 250}};
		html5QrCode.start({facingMode: "environment"}, config, (decodedText, decodedResult) => {
			//console.log('Code matched ' + decodedText);
			//document.getElementById("log").prepend(JSON.stringify(decodedResult));
			//setDeviceId(decodedText);
			window.location.href="/chromebooks?deviceId=" + encodeURIComponent(decodedText);

			// Stop Scanning
			html5QrCode.stop().then((ignore) => {
				// QR Code scanning is stopped.
			}).catch((err) => {
				// Stop failed, handle it.
			});
		}, (error) => {
			//TODO:
		});
	}
</script>

<div class="container">
	<div class="row col-12" style="margin-bottom: 1rem">
		<button type="button" on:click={fakeScan}>Fake Scan</button>
		<button type="button" on:click={clear}>Clear</button>
	</div>

	<!--	<div class="row">-->
	<!--		<div use:scanner id="reader" width="300px"></div>-->
	<!--	</div>-->
	<div class="row col-12">
		<a href="#" on:click={scanner}>Scan</a>
<!--		<button type="button" on:click={scanner}>Scan</button>-->
		<div id="reader" width="250px"></div>
	</div>
	<br/>
	<div class="row col-12">
		<div id="log" class="col-12">
		</div>
	</div>

	<div class="row col-12">
		<ul>
			{#each chromebookData as data}
				<li>{data.email}<br/>{data.serial}<br/>{new Date(data.startTime).toLocaleDateString("en-US") + "-" + new Date(data.endTime).toLocaleDateString("en-US")}</li>
			{/each}
		</ul>
	</div>
</div>
