//@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
				})
			}
		});
	})
}

var showSystemTables = false
var systemTablesSchemas = ["SYSCAT", "SYSIBM", "SYSIBMADM", "SYSSTAT", "SYSTOOLS", "SYSPUBLIC", "", ""]

var ignoreTables = ["EOSLOG.CONFIG_TBL", "EOSLOG.IMAGES_TBL", /*"EOSLOG.LAYERHWIF_TBL", "EOSLOG.LAYERHWI_TBL"*/]

var getLatest = true

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
		if((showSystemTables || tableNameFull == "SYSCAT.TABLES" || !systemTablesSchemas.includes(tableSchema)) && !ignoreTables.includes(tableNameFull)){
			console.log(tableNameFull)
			try{
				//var rows = await queryAsync("select * from " + tableName)
				var result = await queryAsync("Select distinct(name), ColType, Length from Sysibm.syscolumns where tbname = '" + tableName + "';")
				//console.log(result.rows)
				var timestampColumn = ""
				var columns = []
				for(var y in result.rows){
					var colName = result.rows[y].NAME 
					if(colName.indexOf("TIMESTAMP")!= -1){
						timestampColumn = colName
					}
					columns.push(colName + "(" + result.rows[y].COLTYPE.trim() + ") ")
				}
				result = await queryAsync("Select * from " + tableNameFull + (timestampColumn ? " ORDER BY " + timestampColumn + " DESC" : "") + " FETCH FIRST 2 ROWS ONLY;")
				
				/*var maxSizes = []
				for(var y in columns){
					maxSizes.push(columns[y].length + 2)
				}
				for(var y in result.rows){
					var id = 0;
					for(var z in result.rows[y]){
						maxSizes[id] = Math.max(maxSizes[id], String(result.rows[y][z]).trim().length + 1)
						id++
					}
				}*/
				console.log(columns.join(" "))
				console.log("Row Count:", tables[x].CARD)
				//var rowCount = await queryAsync("select COUNT(*) from " + tableNameFull)
				//console.log("Row Count:", rowCount.rows[0]["1"])
				console.log(result.rows)
			}catch(err){
				console.log("Error: " + err.message)
			}
			console.log("")
			console.log("")
		}
	}
	// connection.query("select tabname from syscat.tables",function (err, rows, sqlca){
	// 	console.log(err, rows, sqlca)
	// });
})()
