<!DOCTYPE html>
<html>

<head>
	<title>Update firmware</title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script type="text/javascript" src="../jquery.js"></script>
	<script type="text/javascript">


		var xhr = new XMLHttpRequest();

		function doReboot() {
			xhr.open("GET", "/flash/reboot");
			xhr.onreadystatechange = function () {
				if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
					window.setTimeout(function () {
						location.reload(true);
					}, 3000);
				}
			}
			xhr.send();
		}

		function setProgress(amt) {
			$("#progressbarinner")[0].style.width = String(amt * 200) + "px";
		}

		function doUpgrade() {
			var f = $("#file")[0].files[0];
			if (typeof f == 'undefined') {
				$("#remark")[0].innerHTML = "Can't read file!";
				return
			}
			xhr.onreadystatechange = function () {
				console.log("Ready state changed: " + xhr.readyState);
				if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
					setProgress(1);
					let response = JSON.parse(xhr.responseText);
					if (!response["success"]) {
						$("#remark")[0].innerHTML = "Error: " + xhr.responseText;
					} else {
						$("#remark")[0].innerHTML = "Uploading done. Rebooting.";
						doReboot();
					}
				}
			}
			if (typeof xhr.upload.onprogress != 'undefined') {
				xhr.upload.onprogress = function (e) {
					console.log("Upload progress: " + e.loaded + " / " + e.total);
					setProgress(e.loaded / e.total);
				}
			}
			xhr.open("POST", "/flash/upload");

			xhr.send(f);
			return false;
		}


		window.onload = function (e) {
			xhr.open("GET", "/flash/init");
			xhr.onreadystatechange = function () {
				if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) {
					var txt = "Please upload " + xhr.responseText + " or ota file.";
					$("#remark")[0].innerHTML = txt;
					setProgress(0);
				}
			}
			xhr.send();
		}

	</script>
</head>

<body>
	<div id="main">
		<h1>Update firmware</h1>
		<div id="remark">Loading...</div>
		<input type="file" id="file" />
		<input type="submit" value="Update!" onclick="doUpgrade()" />
		<div id="progressbar">
			<div id="progressbarinner"></div>
		</div>
	</div>
</body>