const flask = getEditor("#code", "sql")
const config = { locateFile: function() {return ""} }
var htmlConsole = document.getElementById("console")

function run() {
	initSqlJs(config).then(function(SQL) {
		let db = new SQL.Database()

		try {
			var res = db.exec(flask.getCode())
		}
		catch (e) {
			printErr(e)
		}
		printRes(res)

		db.close()
	})
}

function printRes(res) {
	let message = ""
	let nres = res.length
	for(let i = 0; i < nres; i++) {
		let columns = res[i].columns
		let rows = res[i].values
		let ncol = columns.length
		let nrow = rows.length
		message = message + "<table><tr>"
		for(let j = 0; j < ncol; j++) {
			message = message + "<th>" + columns[j] + "</th>"
		}
		message = message + "</tr>"
		for(let j = 0; j < nrow; j++) {
			let row = rows[j]
			message = message + "<tr>"
			for(let k = 0; k < ncol; k++) {
				message = message + "<td>" + row[k] + "</td>"
			}
			message = message + "</tr>"
		}
		message = message + "</table>"
	}
	htmlConsole.innerHTML = message
}

function printErr(e) {
	document.getElementById("console").innerHTML = "<div class=\"error\">" + e + "</div>"
}
