var slLib = $.import("uniorg.ServiceLayer", "B1SLLogic");
var slDest = $.import("uniorg.destinations", "uodestlib");
var datetimelib = $.import("uniorg.libs", "datetime");

var outMessages = [];
var output = {};
var outMsg = {};
var outStatus = "success";
var myDebug = {};
var SESSIONID = "";
var NODEID = "";
var slLoggedIn = false;
var UserName = slDest.uniorg_eon_nice_v1_UserName;
var UserPass = slDest.uniorg_eon_nice_v1_UserPass;
var UserComp = slDest.uniorg_eon_nice_v1_UserComp;
var ContractUDOID = "EON_CONTR";

var service_version = '1.0';

var debugLevel = 0;
switch ($.request.parameters.get("debug")) {
	case "true":
	case "yes":
	case "1":
		debugLevel = 1;
		break;
	case "full":
	case "2":
		debugLevel = 2;
		break;
}

if (debugLevel > 1) {
	myDebug.requestParams = $.request.parameters;
}

function setOutputMessage() {
	output.status = outStatus;
	if (debugLevel > 0) {
		output.debugInfos = myDebug;
	}
	output.messages = outMessages;
	$.response.contentType = "application/json";
	$.response.setBody(JSON.stringify(output));
	$.response.status = $.net.http.OK;
}

function exceptionHandler(ex) {
	if (outMsg.method) {
		outMessages.push(outMsg);
	}
	outMsg = {};
	outMsg.method = "exceptionHandler";
	outMsg.status = "error";
	outMsg.message = ex.toString();
	if (debugLevel > 0) {
		outMsg.exceptionInfo = {};
		outMsg.exceptionInfo.name = ex.name;
		outMsg.exceptionInfo.message = ex.message;
		outMsg.exceptionInfo.fileName = ex.fileName;
		outMsg.exceptionInfo.lineNumber = ex.lineNumber;
		outMsg.exceptionInfo.columnNumber = ex.columnNumber;
		outMsg.exceptionInfo.stack = ex.stack;
		//outMsg.exceptionInfo.source = ex.toSource();
	}
	outMessages.push(outMsg);
	outStatus = "error";
	output.status = outStatus;
	if (debugLevel > 0) {
		output.debugInfos = myDebug;
	}
	output.messages = outMessages;

	var errbody = JSON.stringify(output);
	$.response.contentType = 'application/json';
	$.response.setBody(errbody);
	$.response.status = $.net.http.INTERNAL_SERVER_ERROR;

	try {
		if (slLoggedIn) {
			slLib.SLLogout(SESSIONID, NODEID);
		}
	} catch (e) {

	}
}

function slLogin() {
	var loginResult = false;
	var loginInfo = {};
	loginInfo.UserName = UserName;
	loginInfo.Password = UserPass;
	loginInfo.CompanyDB = UserComp;

	// SL LOGIN          
	var response = slLib.SLLogin(JSON.stringify(loginInfo), null, null);

	// B1SESSION and ROUTEID cookies returned by Login
	for (var j in response.cookies) {
		if (response.cookies[j].name == "B1SESSION") {
			SESSIONID = response.cookies[j].value;
			//output.SessionID = SESSIONID;
		} else if (response.cookies[j].name == "ROUTEID") {
			NODEID = response.cookies[j].value;
			//output.NodeID = NODEID;
		}
	}

	var loginResponse;
	try {
		loginResponse = JSON.parse(response.body.asString());
	} catch (e) {
		loginResponse = response.body.asString();
	}

	if (debugLevel > 1) {
		myDebug.loginInfo = loginInfo;
	}
	myDebug.loginResponse = loginResponse;
	if (response.status === 200) {
		loginResult = true;
	} else {
		outMsg = {};
		outMsg.method = "login";
		outMsg.status = "error";
		outMsg.message = loginResponse;
		outMessages.push(outMsg);
		outStatus = "error";
	}
	return loginResult;
}

function getViewData() {
	var rsMsg = {};
	var conn = $.db.getConnection();
	var pstmt;
	var query =
		'SELECT "DocEntry", "ObjType", "DocNum", U_EON_CONTRACT, U_EON_PERIOD_FROM, U_EON_PERIOD_TO, "DocDate", "DocTotal" from A19753_EON_P01.V_UO_LOST_CONTRACT_HISTORY_RECORDS';
	pstmt = conn.prepareStatement(query);
	var rs = pstmt.executeQuery();
	var rsmd = rs.getMetaData();
	var colCount = rsmd.getColumnCount();
	var rc = 0;
	var rows = [];
	while (rs.next()) {
		var row = {};
		rc++;
		for (var c = 1; c <= colCount; c++) {
			var colName = rsmd.getColumnName(c);
			var colType = rsmd.getColumnTypeName(c);
			switch (colType) {
				case 'TINYINT':
				case 'SMALLINT':
				case 'INT':
				case 'INTEGER':
				case 'BIGINT':
					row[colName] = rs.getInteger(c);
					break;
				case 'DECIMAL':
					row[colName] = rs.getDecimal(c);
					break;
				case 'REAL':
				case 'DOUBLE':
				case 'FLOAT':
					row[colName] = rs.getDouble(c);
					break;
				case 'NVARCHAR':
				case 'NCHAR':
				case 'SHORTTEXT':
					row[colName] = rs.getNString(c);
					break;
				case 'VARCHAR':
				case 'CHAR':
					row[colName] = rs.getString(c);
					break;
				case 'BINARY':
				case 'VARBINARY':
					row[colName] = rs.getBString(c);
					break;
				case 'DATE':
					row[colName] = rs.getDate(c);
					break;
				case 'TIME':
					row[colName] = rs.getTime(c);
					break;
				case 'TIMESTAMP':
					row[colName] = rs.getTimestamp(c);
					break;
				case 'CLOB':
					row[colName] = rs.getClob(c);
					break;
				case 'NCLOB':
				case 'TEXT':
					row[colName] = rs.getNClob(c);
					break;
				case 'BLOB':
					row[colName] = rs.getBlob(c);
					break;
				case 'SECONDDATE':
					row[colName] = rs.getSeconddate(c);
					break;
			}
		}
		rows.push(row);
	}
	rsMsg.rowCount = rc;
	rsMsg.rows = rows;
	rs.close();
	pstmt.close();
	conn.close();
	return rsMsg;
}

function repairContractHistory() {
	var docData = getViewData();
	myDebug.docData = docData;
    var startTS = new Date();
	if (docData.rowCount === 0) {
		outMsg = {};
		outMsg.method = "updateContract";
		outMsg.result = "nothing to do";
		outMessages.push(outMsg);
	} else {
		slLogin();

		outMsg = {};
		outMsg.method = "updateContract";
		outMsg.results = [];

		docData.rows.forEach(function(row) {
			var result = {};
			var slContractObj = {
				EON_CONTRACT_BILLCollection: [
					{
						U_PERIOD_FROM: datetimelib.convertToISODate(row.U_EON_PERIOD_FROM),
						U_PERIOD_TO: datetimelib.convertToISODate(row.U_EON_PERIOD_TO),
						U_DOCDATE: datetimelib.convertToISODate(row.DocDate),
						U_DOCTOTAL: row.DocTotal,
						U_OBJTYPE: row.ObjType,
						U_DOCENTRY: row.DocEntry,
						U_DOCNUM: row.DocNum
			        }
			    ]
			};
			result.slContractObj = slContractObj;
			var responseContract = slLib.patchDynamicEntity('EON_CONTR', row.U_EON_CONTRACT, JSON.stringify(slContractObj), SESSIONID, NODEID,
				false);
			if (responseContract.status >= 200 && responseContract.status < 300) {
				result.status = 'success';
			} else {
				result.success = 'failure';
				outStatus = 'error';
				if (responseContract.body) {
					try {
						result.slResponse = JSON.parse(responseContract.body.asString());
					} catch (e) {
						result.slResponse = responseContract.body.asString();
					}
				} else {
					result.slResponse = responseContract;
				}
			}

			outMsg.results.push(result);
		});
        output.durationMilliseconds = new Date() - startTS;
		outMessages.push(outMsg);
    
		try {
			if (slLoggedIn) {
				slLib.SLLogout(SESSIONID, NODEID);
			}
		} catch (e) {}
	}
}

//testmain();

// begin org
try {
	repairContractHistory();
} catch (e) {
	exceptionHandler(e);
}
setOutputMessage();
//ende org