function get(url, whendone, errfunction) {
	var x = new XMLHttpRequest()
	x.open("GET", url)
	x.timeout = 15 * 1000
	x.responseType = "json"
	x.onload = function() { whendone(x) }
	if (errfunction) {
		x.ontimeout = function(e) { errfunction(" timed out") }
		x.onerror = function(e) { errfunction(" error") }
	}
	x.send()
}

function collapse() {
	this.innerHTML = "expand"
	this.parentElement.nextElementSibling.style.display = "none"
	this.onclick = expand
	let cid = this.parentElement.parentElement.id
	if (!collapsedSet[cid]) {
		collapsedSet[cid] = true
		localStorage.setItem("collapsed", Object.keys(collapsedSet).join(" "))
	}
}
function expand() {
	this.innerHTML = "collapse"
	this.parentElement.nextElementSibling.style.display = "block"
	this.onclick = collapse
	let cid = this.parentElement.parentElement.id
	delete collapsedSet[cid]
	localStorage.setItem("collapsed", Object.keys(collapsedSet).join(" "))
}

let collapsedSet = {}

function domdone() {
	let collapsed = localStorage.getItem("collapsed") || ""
	let carr = collapsed.split(" ")
	if (carr.length > 64) {
		carr = carr.slice(-64)
	}
	carr.forEach(cid => collapsedSet[cid] = true)
	let els = document.getElementsByClassName("collapselink")
	for (let i = 0; i < els.length; i++) {
		var el = els[i]
		let cid = el.parentElement.parentElement.id
		if (collapsedSet[cid]) {
			collapse.call(el)
		} else {
			el.onclick = collapse
		}
	}
	let btn = document.getElementById("btnrefresh")
	if (btn) {
		btn.onclick = function() {
			btn.innerHTML = "getting"
			let toplink = btn.dataset.toplink
			let url = `/refresh?after=${toplink}`
			get(url, refreshLinks)
		}
	}
}

function refreshLinks(xhr) {
	let resp = xhr.response

	let newlinks = resp.newlinks
	let el = document.getElementById("linkholder")
	el.insertAdjacentHTML("afterbegin", newlinks)

	let toplink = resp.toplink
	let btn = document.getElementById("btnrefresh")
	btn.innerHTML = "updated"
	setTimeout(() => btn.innerHTML = "refresh", 500)
	btn.dataset.toplink = toplink

	let cmtcnts = resp.commentcounts
	for (let cmt in cmtcnts) {
		let cnt = cmtcnts[cmt]
		let el = document.getElementById(cmt)
		if (el) el.innerText = cnt
	}
	let notifcount = resp.notifcount
	el = document.getElementById("notifholder")
	if (notifcount)
		el.innerText = `notifs (${notifcount})`
	else
		el.innerText = "notifs"
}

document.addEventListener("DOMContentLoaded", domdone)

function hotkey(e) {
    if (e.ctrlKey || e.altKey)
        return
    if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement)
        return
    let next
    switch (e.code) {
    case "Escape":
        break
    case "KeyR":
        var el = document.getElementById('btnrefresh')
        if (el) {
            el.click()
        }
        break
    }
}

document.addEventListener("keydown", hotkey)
