var lastPortTestStatus = "";

function updatePortTestStatus(status) {

	var spinner = document.getElementById("nodeAgentTestSpinner");
	var arrow = document.getElementById("nodeAgentTestArrow");
	var wan = document.getElementById("nodeAgentTestWan");
	var cloud = document.getElementById("nodeAgentTestCloud");
	var failed = document.getElementById("nodeAgentTestFailed");
	var idleState = document.getElementById("nodeAgentTestStateIdle");
	var successState = document.getElementById("nodeAgentTestStateSuccess");
	var failedState = document.getElementById("nodeAgentTestStateFailed");
	var runningState = document.getElementById("nodeAgentTestStateRunning");
	var check = document.getElementById("nodeAgentTestCheck");
	var retry = document.getElementById("retry");
	var nextButton = document.getElementById("nextButton");
	
	/* Alwawys upated */
	error.innerText =  status.error;
	document.getElementById("wan").innerText = status.addresses[0] + ":" + status.port;
	
	/* Only update when state changes */
	if(status.state != lastPortTestStatus) {
		
		lastPortTestStatus = status.state;

		/* Reset */

		spinner.classList.remove("d-none");
		failed.classList.remove("d-none");
		failed.classList.remove("d-none");
		failedState.classList.remove("d-none");
		idleState.classList.remove("d-none");
		successState.classList.remove("d-none");
		runningState.classList.remove("d-none");
		arrow.classList.remove("fa-beat-fade");
		wan.classList.remove("bg-dark");
		wan.classList.remove("bg-danger");
		wan.classList.remove("bg-success");
		cloud.classList.remove("bg-dark");
		cloud.classList.remove("bg-primary");
		retry.classList.remove("d-none");
		check.classList.remove("d-none");
		nextButton.setAttribute("disabled", "");
	
		if(status.state === "IDLE") {
			failed.classList.add("d-none");
			failedState.classList.add("d-none");
			successState.classList.add("d-none");
			runningState.classList.add("d-none");
			retry.classList.add("d-none");
			check.classList.add("d-none");
			wan.classList.add("bg-dark");
			cloud.classList.add("bg-dark");
		}
		else if(status.state === "RUNNING") {
			arrow.classList.add("fa-beat-fade");
			cloud.classList.add("bg-primary");
			wan.classList.add("bg-dark");
			failed.classList.add("d-none");
			failedState.classList.add("d-none");
			successState.classList.add("d-none");
			idleState.classList.add("d-none");
			retry.classList.add("d-none");
			check.classList.add("d-none");
		}
		else {
			idleState.classList.add("d-none");
			runningState.classList.add("d-none");
			spinner.classList.add("d-none");
			cloud.classList.add("bg-dark");
			check.classList.remove("d-none");
			if(status.state === "SUCCESS") {
				failedState.classList.add("d-none");
				failed.classList.add("d-none");
				wan.classList.add("bg-success");
				nextButton.removeAttribute("disabled");
				
				/* Need to add event, as disabled buttons dont get them and the
				   button may have been disabled at the start */
				   
				nextButton.addEventListener("click", (e) => {
					e.preventDefault();
					Wizard.next();
				});
			}
			else {
				successState.classList.add("d-none");
				wan.classList.add("bg-danger");
			}
		}
	
	}
		
}

function doPortTestAPI(uri, onSuccess, method) {
	/* TODO this really needs to be abstacted somewhere, generic XMLHttpRequest helper */
	const xhr = new XMLHttpRequest();
	xhr.open(method ? method : "GET", uri);
	xhr.responseType = "json";
	xhr.onload = function(e) {
		if (xhr.status === 200) {
			if (xhr.response.redirect) {
				window.location.href = xhr.response.location;
			} else {
				if (xhr.response.success) {
					onSuccess(xhr.response);
				}
				else {
					portTestError(xhr.response.message);
				}
			}
		}
	};
	xhr.send();
}

function startPortTest() {
	var portTest = document.getElementById("portTest");
	doPortTestAPI("/app/api/port-test/" + 
		portTest.dataset.agent + "/" + 
		portTest.dataset.port + "/" + 
		portTest.dataset.address, response => {
		updatePortTestStatus(response.resource);
	});
}

function retryPortTest() {
	var portTest = document.getElementById("portTest");
	doPortTestAPI("/app/api/port-test-reset/" + 
		portTest.dataset.agent, response => {
		updatePortTestStatus(response.resource);
	});
}

function portTestError(msg) {

	/* TODO this really needs to be abstacted somewhere,
	programatically create client side alerts */
	var errIcon = document.createElement("i");
	errIcon.classList.add(document.getElementsByTagName('body')[0].getAttribute('data-iconset'));
	errIcon.classList.add("fa-shield-exclamation");
	errIcon.classList.add("me-1");

	var errSpan = document.createElement("span");
	errSpan.innerHTML = msg;

	var error = document.createElement("div");
	error.classList.add("alert");
	error.classList.add("alert-danger");
	error.appendChild(errIcon);
	error.appendChild(errSpan);

	var feedback = document.getElementById("feedback");
	feedback.innerHTML = "";
	feedback.appendChild(error, a.parentElement.parentElement.childNodes[0]);
}

function refreshPortTestStatus() {
	var portTest = document.getElementById("portTest");
	doPortTestAPI("/app/api/port-test/" + portTest.dataset.agent, response => {
		updatePortTestStatus(response.resource);
		if(response.resource.state === "IDLE") {
			startPortTest();
		}
	});
}

window.setInterval(() => {
	refreshPortTestStatus();
}, 10000);

document.getElementById("retry").addEventListener("click", e => retryPortTest());
refreshPortTestStatus();