// deno
import { DOMParser } from 'https://deno.land/x/deno_dom/deno-dom-wasm.ts'

function getdompareser(html)
{
	const parser = new DOMParser()
	return parser.parseFromString(html, "text/html")
}

function gettables(doc)
{
	return [...doc.getElementsByTagName("h2")].map(h2 => h2.id)
}

function gettable(doc, table, notes)
{
	const result = []
	const items = [...doc.getElementById(table).nextSibling.nextSibling.nextSibling.firstChild.children[0].children]
	const header = [...items.shift().children].map(h => h.textContent)
	items.forEach(elt => {
		const item = {}
		const columns = [...elt.children]
		header.forEach( (h,i) =>
		{
			item[h] = columns[i].textContent
		})
		if (item.Name)
		{
			const sup = parseInt(item.Name.split(" ").pop())
			if (!isNaN(sup))
			{
				item.Notes = notes[sup - 1]
				item.Name = item.Name.substr(0, item.Name.length - 2)
			}
		}
		result.push(item)
	})
	return result
}

function getnotes(doc)
{
	const lastsup = [...doc.getElementsByTagName("sup")].pop()
	if (!lastsup)
	{
		return []
	}
	return lastsup.parentElement.textContent.split("\n")
	.filter(i => i.length)
	.map(i => i.substr(3).trim())
}

async function getpage(url)
{
	const result = {}
	const response = await fetch(url)
	const html = await response.text()

	const doc = getdompareser(html)
	const notes = getnotes(doc)
	const tables = gettables(doc)
	tables.forEach(table =>
	{
		result[table] = gettable(doc, table, notes)
	})
	return result
}

function format(equipment, exclude)
{
	const result = []

	Object.keys(equipment).forEach(table => {
		const columnsizes = {}
		result.push(table.toUpperCase())
		const items = equipment[table]

		// exclude
		items.forEach(item => {
			exclude.forEach(name => {
				delete item[name]
			})
		})

		// init sizes
		items.forEach(item =>
		{
			Object.keys(item).forEach(columnname => {
				columnsizes[columnname] = columnsizes[columnname] || columnname.length
				columnsizes[columnname] = Math.max(columnsizes[columnname], (item[columnname] || "").length)
			})
		})
		
		// write header
		let line = ""
		Object.keys(columnsizes).forEach(columnname => {
			const size = columnsizes[columnname]
			line += columnname + " ".repeat((Math.max(0, size - columnname.length))) + "|"
		})
		result.push(line)

		// write lines
		items.forEach(item => {
			let line = ""
			Object.keys(columnsizes).forEach(columnname => {
				const size = columnsizes[columnname]
				const value = (item[columnname] || "").replace("\n", " ")
				line += value + " ".repeat(Math.max(0, size - value.length)) + "|"
			})
			result.push(line)
		})
		result.push(" ")
	})

	return result.join("\n")
}

async function getdata(configname)
{
	const pages = configs[configname].pages
	let result = {}
	const root = "https://mikesrpgcenter.com"
	for (const index in pages)
	{
		const page = pages[index]
		const pagedata = await getpage([root, configname, page].join("/") + ".html")
		result = {...result, ...pagedata}
	}
	return result
}

function output(stringresult, configname)
{
	//console.log(stringresult)
	Deno.writeTextFile(configname + ".txt", stringresult)
}

const configs = {
	ffantasy: { pages: ["weapons", "armor", "blackmagic", "whitemagic"], exclude: ["Found", "Sold", "Available", "Notes", "Cost", "Ni", "WM", "WW", "BM", "BW", "Th", "BB", "Ma"] },
	dw3: { pages: ["armor", "weapons"], exclude: [] },
}

for (const configname in configs) {
	const data = await getdata(configname)
	const stringresult = format(data, configs[configname].exclude)
	output(stringresult, configname)
}