/**
 * Special logic for the Nodal Agent Choice wizard section.
 * 
 * It basically refreshes  the list of nodes, and decorates them with an
 * icon and the remote address if known.
 */


/**
 * Update the node agents, adding new ones, removing  those that are now 
 * gone, and updating the status of those that exist.
 * 
 * @param agents array of objects contain agent summary data
 */
function updateAvailableNodeAgents(agents) {
	var found = [];

    if(agents.length > 0)
        document.getElementById("refresher").classList.add("d-none");
    else
        document.getElementById("refresher").classList.remove("d-none");
    	
	agents.forEach(agent => {
		found.push(agent.uuid);
		
		var itemElement = document.querySelector("[data-resourcekey=\"" + agent.uuid + "\"]");
		if(!itemElement) {

			var flexInner = document.createElement("div");
			flexInner.classList.add("flex-grow-1");
			flexInner.innerText = agent.name;

			var liDiv = document.createElement("div");
			liDiv.classList.add("d-flex");
			liDiv.appendChild(flexInner);
			
			itemElement = document.createElement("a");
			itemElement.href = "#";
			itemElement.setAttribute("data-resourcekey", agent.uuid);
			itemElement.classList.add("dropdown-item");
			itemElement.appendChild(liDiv);
			
			/* TODO not great, we need to add event handlers back because Footer.js 
			        doesnt watch DOM modifications. There should be a general solution
					to this */
			itemElement.addEventListener("click", (e) => {
				e.preventDefault();
				var target = itemElement.dataset.dropdownMenuItemTarget;
				var value = itemElement.dataset.resourcekey;
				document.querySelector("[name=nodeAgent]").setAttribute("value", value);
				var otherItems = [...document.querySelectorAll("[data-dropdown-menu-item-target=\"" + target + "\"]")];
				otherItems.forEach(otherItem => {
					var otherVal = otherItem.dataset.resourcekey;
					otherItem.classList.remove("active");
					if(val === otherVal)
						otherItem.classList.add("active");
				});
				
			});
			
			var li = document.createElement("li");
			li.appendChild(itemElement);
			
			var parent = document.querySelector(".nodeAgentDropdown");
			parent.appendChild(li);
		}
		
		var flexBox  = itemElement.querySelector(".d-flex");
		
		var icon = flexBox.querySelector("i");
		if(!icon) {
			icon = document.createElement("i");
			var iconInner = document.createElement("div");
			iconInner.classList.add("pe-2");
			iconInner.appendChild(icon);
			flexBox.prepend(iconInner);
		}

		var statusText = flexBox.querySelector("span");
		if(!statusText) {
			statusText = document.createElement("span");
			statusText.classList.add("text-muted");
			var statusInner = document.createElement("div");
			statusInner.appendChild(statusText);
			flexBox.appendChild(statusInner);
		}
		
	    icon.classList = [];

		itemElement.dataset.ready = agent.online && agent.ok;
		
		if(agent.online) {
			if(agent.ok) {
				itemElement.removeAttribute("disabled");
				icon.classList.add(document.getElementsByTagName('body')[0].getAttribute('data-iconset'), "fa-circle-nodes", "text-success");
			}
			else {
				itemElement.setAttribute("disabled", "");
				icon.classList.add(document.getElementsByTagName('body')[0].getAttribute('data-iconset'), "fa-circle-nodes", "text-warning");
			}

			statusText.innerText = agent.remoteAddress;
		}
		else {
			itemElement.setAttribute("disabled", "");
			icon.classList.add(document.getElementsByTagName('body')[0].getAttribute('data-iconset'), "fa-circle-nodes", "text-danger");
			statusText.innerText = "";
		}

	});
	
	var itemElements = [...document.querySelectorAll(".nodeAgentDropdown .dropdown-item")];
	itemElements.forEach(item => {
		if(!found.includes(item.dataset.resourcekey)) {
			item.remove();
		}
	});
	
	var clazzes = document.querySelector(".nodeAgentDropdownEmpty").classList; 
	if(agents.length == 0 && clazzes.contains("d-none")) {
		clazzes.remove("d-none");
	}
	else if(agents.length > 0 && !clazzes.contains("d-none")) {
		clazzes.add("d-none");
	}
}

/**
 * Initate the JSON API call to get the current nodal agent list, and update 
 * the UI when thhe response is received. * 
 */
function refreshAvailableNodeAgents() {

	/* TODO this really needs to be abstacted somewhere, generic XMLHttpRequest helper */
	const xhr = new XMLHttpRequest();
	xhr.open("GET", "/app/api/nodes");
	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) {
					updateAvailableNodeAgents(xhr.response.resources);
				}
				else {
					/* 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 = xhr.response.message;

					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]);
				}
			}
		}
	};
	xhr.send();
}

window.setInterval(() => {
	refreshAvailableNodeAgents();

}, 10000);


refreshAvailableNodeAgents();

