const sprintf = (...[string, ...args]) => {
    return string.replace(/{(\d+)}/g, (match, number) => args[number] ?? match);
}
const getJSON = async url => {
	const resp = await fetch(url)
	const json = await resp.json()
    return json;
}
const createPopup = async id => {
	const asics = await getJSON('/api/asictypes')
	asicoptions = ''
	asics.forEach(elem => {
		asicoptions += sprintf('', elem['key'], elem['value'])
	})
	document.querySelector('body').innerHTML += sprintf(popup, id, asicoptions, 'content')
}
const deletePopup = id => {
	document.querySelector('#popup-' + id).remove()
}
const update = async () => {
	let inner = await getStats()
	document.querySelector('.grid').innerHTML = inner
}
const datafn = async () => {
	// return await getJSON('/api/webinit')
}
const data = datafn()
console.log(data)
const cols = 40
const rows = 40
const css =
	`
	`
const header =
	'
'
const cell =
	''
		+ '{2}'
	+ '
'
const grid =
	''
		+ '{0}'
	+ '
'
const popup =
	''
const getStats = async () => {
	let cells = ''
	let info = await getJSON('/curstatus.json')
	for(let i = 1; i <= cols * rows; i++) {
		if(info.asics[i]?.status == "ok")
			cells += sprintf(cell, i, 'green', info.asics[i]?.hashrate)
		else if(info.asics[i]?.status == "warn")
			cells += sprintf(cell, i, 'yellow', info.asics[i]?.hashrate)
		else if(info.asics[i]?.status == "crit")
			cells += sprintf(cell, i, 'red', info.asics[i]?.hashrate)
		else if(info.asics[i]?.status == "off")
			cells += sprintf(cell, i, 'darkred', '')
		else
			cells += sprintf(cell, i, '', '')
	}
	return cells
}
const run = async () => {
	document.querySelector('body').innerHTML += css
	document.querySelector('body').innerHTML += sprintf(header)
	let inner = sprintf(grid, await getStats())
	document.querySelector('body').innerHTML += inner
	setInterval(async () => {
		await update()
	}, 10000)
}
run()