var REVISION = "9";
var gameState;

function initChangeLog() {
	let xhr = new XMLHttpRequest();
	xhr.open("GET", "changelog.html");
	xhr.onreadystatechange = () => {
		if(xhr.status != 200) {
			console.error("Fail loading of changelog");
			return false;
		}

		document.getElementById("changelog-container").innerHTML = xhr.responseText;
	}
	xhr.send();
}

function initAutoFillLoginForm() {
	let fields = localStorage.getItem("login-field");
	if(fields) {
		fields = JSON.parse(fields);
		$("#welcome-username").val(fields.name);
		$("#welcome-lobby").val(fields.lobby);
	} 
}

function commandBtnProcessing() {
	setInterval(() => {
		let hash = document.location.hash;
		if(hash.indexOf("cmd:") == -1) {
			return;
		}

		document.location.hash = "";
		cmd = hash.split(":")[1];
		gameState.send(cmd);
	}, 200);
}

(function () {

	// Everything that runs as soon as the page loads; sets up the page and handles the
	// connection to the server.

	gameState = new GameState();

	$( document ).ready(function () {
		// Set up the game

		initAutoFillLoginForm();

		$("#welcome-username, #welcome-lobby").on("keyup", function(e) {
			if(e.keyCode === 13) {
				joinGame();
			}
		});

		commandBtnProcessing();

		// Check that the JS and HTML have matching versions
		// (caching is weird)
		var htmlRev = $("#REVISION").val();
		if (htmlRev != REVISION) {
			setTimeout(function() {
				location.reload();
			}, 1500);
			return;
		}

		initChangeLog();
		
		// Load assets
		var assets = [
			"wood.jpg",
			"card_back.png",
			"card_defuse.png",
			"card_exploding.png",
			"card_nope.png",
			"card_skip.png",
			"card_attack.png",
			"card_see3.png",
			"card_favour.png",
			"card_shuffle.png",
			"card_random1.png",
			"card_random2.png",
			"card_random3.png",
			"card_random4.png",
			"card_random5.png",
			"atomic.ogg"
		];
		var promises = [];
		var assetsLoaded = 0;

		for (var i = 0; i < assets.length; i++) {
			(function(url, promise) {
				let ext = url.split(".").pop();
				var el;
				if (ext == "jpg" || ext == "png") {
					el = new Image();
				} else {
					el = new Audio();
				}

				el.onload = function() {
					// Increment the loading counter to convince the user we're doing something
					assetsLoaded += 1;
					document.getElementById("loading-assets").innerHTML = assetsLoaded;

					promise.resolve();
				};
				if (ext == "ogg") {
					el.oncanplaythrough = el.onload;
				}

				el.src = "assets/"+url;

				gameState.loadAsset(url, el);
			})(assets[i], promises[i] = $.Deferred());
		}

		// Once all the promises have resolved (all assets loaded), call the function to 
		// display the welcome page.
		$.when.apply($, promises).done(welcomePage);
	});

	function welcomePage() {
		// Transition loading screen -> welcome page

		$("#welcome-join").bind("click touchstart", joinGame);

		$("#loading").toggleClass("reveal");
		$("#welcome").toggleClass("reveal");
	}

	function joinGame() {
		// Communicate with the server, make sure we join the game ok, render the board

		if (gameState.conn != null) {
			alert(strings["already_connecting"]);
			return;
		}
			
		const defaultLobbyName = "lobby" + Math.floor(Math.random() * 10000);
		const defaultUserName = Math.floor(Math.random() * 10000) + "_guest";

		gameState.lobby = $("#welcome-lobby").val() || defaultLobbyName;
		gameState.name  = $("#welcome-username").val() || defaultUserName;

		localStorage.setItem("login-field", JSON.stringify({
			name: gameState.name,
			lobby: gameState.lobby
		}));

		if (gameState.name.includes(" ")) {
			alert(strings["one_word"]);
			return;
		}
		if (gameState.lobby.includes(" ")) {
			alert(strings["lobby_one_word"]);
			return;
		}

		gameState.conn = new WebSocket("ws://" + location.host + "/ws");

		gameState.conn.onopen = function () {
			gameState.conn.send("join_lobby " + gameState.lobby + " " + gameState.name);
		}

		gameState.conn.onclose = function () {
			alert(strings["conn_closed"]);
			location.reload();
		};

		gameState.conn.onmessage = function(ev) {
			// We wrap this in an anonymous function so that 'this'
			// will refer to the GameState object and not the WebSocket
			// (I don't have a clue how javascript OOP works)
			gameState.readFromServer(ev);
		};
	}

	document.addEventListener("DOMContentLoaded", e => {
		document.querySelector(".toggle-gamebar").addEventListener("click", e => {
			document.querySelector("#sidebar").classList.add("show");
		});

		document.querySelector(".toggle-gamelog").addEventListener("click", e => {
			document.querySelector(".game-log-wrap").classList.add("show");
		});

		document.querySelector("#sidebar .btn-close").addEventListener("click", e => {
			document.querySelector("#sidebar").classList.remove("show");
		});

		document.querySelector(".game-log-wrap .btn-close").addEventListener("click", e => {
			document.querySelector(".game-log-wrap").classList.remove("show");
		});
	});
})();
