//@ts-check
var ibmdb = require("ibm_db")
var connectionString = require("./out/connectionstring.js")

console.log("connecting")
var connection = ibmdb.openSync(connectionString)

function queryAsync(query){
	return new Promise(function(resolve,reject){
		connection.query(query,function (err, rows, sqlca){
			//console.log(err, rows, sqlca)
			if(err){
				reject(err)
			}else{
				resolve({
					rows: rows,
					state: sqlca
				})
			}
		});
	})
}

void (async function(){
	//var rows = connection.querySync("list tables for all");
	var tables = connection.querySync("select TABNAME,TABSCHEMA,CARD from syscat.tables");
	tables.sort(function(a,b){
		if(a.TABNAME < b.TABNAME){
			return -1
		}else if(a.TABNAME > b.TABNAME){
			return 1
		}else{
			return 0
		}
	})
	//console.log(tables);
	for(var x in tables){
		var tableName = tables[x].TABNAME.trim()
		var tableSchema = tables[x].TABSCHEMA.trim()
		var tableNameFull = tableSchema + "." + tableName
		//@ts-ignore
		if(tableNameFull == process.argv[2]){
			console.log(tableNameFull)
			try{
				var result = await queryAsync("Select distinct(name), ColType, Length from Sysibm.syscolumns where tbname = '" + tableName + "';")
				var columns = []
				for(var y in result.rows){
					columns.push(result.rows[y].NAME + "(" + result.rows[y].COLTYPE.trim() + ") ")
				}
				result = await queryAsync("Select * from " + tableNameFull + ";")
				console.log(columns.join(" "))
				console.log("Row Count:", tables[x].CARD)
				console.log(JSON.stringify(result.rows,null,2))
			}catch(err){
				console.log("Error: " + err.message)
			}
		}
	}
})()
