var failures = 0;
var timeouts = [1, 5, 10, 60, 300];
var curerror = null;

function fromtext(text) {
    return(new DOMParser().parseFromString(text, "text/html").body.firstChild);
}

function got_update(data) {
    failures = 0;
    clear_error();
    if(data != "") {
	var el = fromtext(data);
	var status = document.getElementById("status");
	status.parentNode.replaceChild(el, status);
    }
    setTimeout(queue_update, 2500);
}

function clear_error() {
    if(curerror !== null) {
	curerror.remove();
	curerror = null;
    }
}

function got_error(exc) {
    clear_error();
    var err = fromtext("<p>(Currently not updating live)</p>");
    document.getElementById("status").append(err);
    curerror = err;
    var to = failures++;
    if(to >= timeouts.length)
	to = timeouts.length - 1;
    setTimeout(queue_update, timeouts[to] * 1000);
}

function queue_update() {
    var url = "/portal/index/status";
    var status = document.getElementById("status");
    var seq = status.getAttribute("sequence")
    if(seq)
	url += "?seq=" + seq;
    fetch(url).then(response => {
	if(response.ok) {
	    return(response.text());
	} else {
	    throw(new Error("status fetch error: " + response.statusText));
	}
    }).then(got_update).catch(got_error);
}

document.addEventListener("DOMContentLoaded", queue_update);
