package ibase.webitm.bean;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.naming.InitialContext;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import ibase.ejb.CommonDBAccessEJB;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMUserAuditBrowFormEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class ITMUserAuditBeanTest implements Serializable {

	  
	String objName = "user_audit_trail";
	String refID;
	String chgID;
	String recObjName;
	String pContext = "1";
	String objContext = "1";
	String editFlag = "V";
	String reqParamStr = "";
	String user_lang = "en";
	String user_country = "US";
	ibase.utility.UserInfoBean userInfo=null;
	String defaultPath = CommonConstants.APPLICATION_CONTEXT + CommonConstants.ITM_CONTEXT + File.separator;

        
	public void setRequestParamStr(String reqParamStr){
		if( reqParamStr != null && ! "null".equalsIgnoreCase(reqParamStr) && reqParamStr.length() > 0 ){
			this.reqParamStr = reqParamStr;
		}
	}

	public void setUserInfo( ibase.utility.UserInfoBean userInfo ){
		this.userInfo = userInfo;
	}

	public String getXMLStrBrow(String output)throws ITMException{
		
		BaseLogger.log("2", userInfo, null,"Getting Brow Form XML String...."+output);
		InitialContext ctx = null;
		String retData = null;
		try{      
			ITMUserAuditBrowFormEJB ITMBrowForm = new ITMUserAuditBrowFormEJB();
			retData = ITMBrowForm.getBrowForm(this.objName, this.objContext, (this.objName + this.pContext + this.objContext), this.reqParamStr, this.userInfo);
			if( "HTML".equalsIgnoreCase(output)  ) {
				try {
					TransformerFactory tFactory = TransformerFactory.newInstance();
					
					String xslFile = new E12GenericUtility().readFile(CommonConstants.APPLICATION_CONTEXT + CommonConstants.ITM_CONTEXT + File.separator+"xsl"+File.separator+"user_audit_trail11_en_US_V.xsl");
					Transformer transformer = tFactory.newTransformer(new  StreamSource(new ByteArrayInputStream(xslFile.getBytes())));
			        ByteArrayOutputStream bos = new ByteArrayOutputStream();
			        transformer.transform( new DOMSource( new E12GenericUtility().parseString( retData )), new StreamResult(bos));
			        retData = bos.toString();
				}
				catch ( Exception e ){
					e.printStackTrace();
				}
			}
			ITMBrowForm = null;
		}
		catch(ITMException itme){
			BaseLogger.log("0", userInfo, null,"ITMException :ITMAuditBean :getXmlStr :==>");
			throw itme;
		}
		catch(Exception e){
			BaseLogger.log("0", userInfo, null,"Exception :ITMAuditBean :getXmlStr :==>");
			e.printStackTrace();
			throw new ITMException(e);
		}
		BaseLogger.log("2", userInfo, null,"Returning XML String Length :["+retData.length()+"]bytes");
		return retData;
	}
	
	public String getXMLStrDetail()throws ITMException{
		
		BaseLogger.log("2", userInfo, null,"Getting Free Form XML String....");
		InitialContext ctx = null;
		String xmlString = null;
		try{
			
			DBAccessEJB dbAccess = new DBAccessEJB();
			String query = "SELECT CHG_XML FROM AUDIT_TRAIL WHERE CHG_ID = ? AND OBJ_NAME=? AND REF_ID=?";
			
			ArrayList bindVarValues = new ArrayList();
			ArrayList bindVarTypes = new ArrayList();

			bindVarValues.add(this.chgID);
			bindVarValues.add(this.recObjName);
			bindVarValues.add(this.refID.trim());
			BaseLogger.log("3", userInfo, null,"query "+query);
			BaseLogger.log("3", userInfo, null,"this.chgID ["+this.chgID+"]");
			BaseLogger.log("3", userInfo, null,"this.recObjName ["+this.recObjName+"]");
			BaseLogger.log("3", userInfo, null,"this.refID ["+this.refID+"]");

			bindVarTypes.add("String");
			bindVarTypes.add("String");
			bindVarTypes.add("String");
			
			xmlString = dbAccess.getBlob(query, bindVarValues, bindVarTypes, this.userInfo);
			dbAccess = null;
		}
		catch(ITMException itme){
			BaseLogger.log("0", userInfo, null,"ITMException :ITMAuditBean :getXmlStr :==>");
			throw itme;
		}
		catch(Exception e){
			BaseLogger.log("0", userInfo, null,"Exception :ITMAuditBean :getXmlStr :==>");
			e.printStackTrace();
			throw new ITMException(e);
		}
		BaseLogger.log("2", userInfo, null,"Returning XML String Length :["+xmlString.length()+"]bytes");
		return xmlString;
	}
	
	public String getXMLStrDetail(UserInfoBean userInfo) throws ITMException 
	{ 
		BaseLogger.log("2", userInfo, null,"Getting Free Form XML String....");
		InitialContext ctx = null;
		String xmlString = null;
		try{
			DBAccessEJB dbAccess = new DBAccessEJB();
			String query = "SELECT CHG_XML FROM AUDIT_TRAIL WHERE CHG_ID = ? AND OBJ_NAME=? AND REF_ID=?";
			
			ArrayList bindVarValues = new ArrayList();
			ArrayList bindVarTypes = new ArrayList();

			bindVarValues.add(this.chgID);
			bindVarValues.add(this.recObjName);
			bindVarValues.add(this.refID.trim());

			BaseLogger.log("3", userInfo, null,"query "+query);
			BaseLogger.log("3", userInfo, null,"this.chgID ["+this.chgID+"]");
			BaseLogger.log("3", userInfo, null,"this.recObjName ["+this.recObjName+"]");
			BaseLogger.log("3", userInfo, null,"this.refID ["+this.refID+"]");

			bindVarTypes.add("String");
			bindVarTypes.add("String");
			bindVarTypes.add("String");
			
			xmlString = dbAccess.getBlob(query, bindVarValues, bindVarTypes, userInfo);
			dbAccess = null;
		}
		catch(ITMException itme){
			BaseLogger.log("0", userInfo, null,"ITMException :ITMAuditBean :getXmlStr :==>");
			throw itme;
		}
		catch(Exception e){
			BaseLogger.log("0", userInfo, null,"Exception :ITMAuditBean :getXmlStr :==>");
			e.printStackTrace();
			throw new ITMException(e);
		}
		BaseLogger.log("2", userInfo, null,"Returning XML String Length :["+xmlString.length()+"]bytes");
		return xmlString;
	}
	
	public String getSessionInfoDet(String userId, String fromDate, String toDate) {
		BaseLogger.log("3", null, null, "DFQ Inside getSessionInfoDet::");

		String sessionid = "", chg_user = "", loginstatus = "", chgterm = "", chguser = "", logintime = "",
				xmlbufferdata = "", logoutTime = "";
		java.sql.PreparedStatement pstmt = null;
		Connection con = null;
		ResultSet rs = null;
		Date datee;
		Timestamp fromdate = null, todate = null;
		int dom = 1000;
		
		
		BaseLogger.log("3", null, null, "DFQ after variables before try::");
		BaseLogger.log("3", null, null, "DFQ userid::"+userId);
		BaseLogger.log("3", null, null, "DFQ fromdate::"+fromDate);
		BaseLogger.log("3", null, null, "DFQ above todate::");
		BaseLogger.log("3", null, null, "DFQ todate::"+toDate);


		try {
			
			BaseLogger.log("3", null, null, "DFQ firstline inside try::");
			CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
			 userInfo = commonDBAccessEJB.createUserInfo(userId);
			BaseLogger.log("3", userInfo, null, "DFQ below userinfo creation::" + userInfo);
			ValidatorEJB valejb = new ValidatorEJB();
			valejb.setUserInfo(userInfo);
			con = valejb.getConnection();
			BaseLogger.log("3", userInfo, null, "DFQ above valejb.getconnection()");
			BaseLogger.log("3", userInfo, null, "DFQ below valejb.getconnection()");

			BaseLogger.log("3", userInfo, null, "DFQ fromdate:" + fromDate);
			BaseLogger.log("3", userInfo, null, "DFQ todate::" + toDate);

			String loginTraceSql = "SELECT * FROM LOGINTRACE WHERE LOGIN_STATUS = 'T' AND USERID = ? AND LOGINTIME >= ? AND TRUNC(LOGINTIME) <= ?";
			//String sql2 = "SELECT * FROM LOGINTRACE WHERE LOGIN_STATUS = 'T' AND USERID = ? AND LOGOUTTIME >= ? AND TRUNC(LOGOUTTIME) <= ?";
	
			BaseLogger.log("3", userInfo, null, "DFQ result from sql::" + loginTraceSql);
			//BaseLogger.log("3", userInfo, null, "DFQ result from sql2::" + sql2);

			
			pstmt = con.prepareStatement(loginTraceSql);
			pstmt.setString(1, userId);
			pstmt.setString(2, fromDate);
			pstmt.setString(3, toDate);

			rs = pstmt.executeQuery();

			BaseLogger.log("3", userInfo, null, "DFQ below resultset::" + rs);

			StringBuffer buffer = new StringBuffer();

			while (rs.next()) {
				
				E12GenericUtility genericUtility = new E12GenericUtility();
				sessionid = genericUtility.checkNull(rs.getString("SESSIONID"));
				loginstatus = genericUtility.checkNull(rs.getString("LOGIN_STATUS"));
				chgterm = genericUtility.checkNull(rs.getString("CHG_TERM"));
				logintime = genericUtility.checkNull(rs.getString("LOGINTIME"));
				chg_user = genericUtility.checkNull(rs.getString("USERID"));
				logoutTime = genericUtility.checkNull(rs.getString("LOGOUTTIME"));

				BaseLogger.log("3", userInfo, null, "DFQ sessionid::" + sessionid);
				BaseLogger.log("3", userInfo, null, "DFQ loginstatus::" + loginstatus);
				BaseLogger.log("3", userInfo, null, "DFQ chgterm" + chgterm);
				BaseLogger.log("3", userInfo, null, "DFQ chguser::" + chguser);
				BaseLogger.log("3", userInfo, null, "DFQ logintime::" + logintime);
				BaseLogger.log("3", userInfo, null, "DFQ logoutime::" + logoutTime);

				
				
				String newDate = newDateFormat(logintime);
				BaseLogger.log("3", userInfo, null, "DFQ newdate from newdateformat method" + newDate);

				String newDtFOrmatlogoutTime = newDateFormatLogoutTime(logoutTime);
				BaseLogger.log("3", userInfo, null, "DFQ newdate from newDtFOrmatlogoutTime method" + newDtFOrmatlogoutTime);


				
				buffer.append("<Detail1 dbID='' domID='" + dom + "' objName='user_audit_trail' objContext='1'>\r\n");
				buffer.append("<attribute pkNames='' status='O' updateFlag='N' selected='N' />\r\n");
				buffer.append("<chg_id><![CDATA[2]]></chg_id>\r\n");
				buffer.append("<obj_name><![CDATA[Login Session Info]]></obj_name>\r\n");
				buffer.append("<ref_id><![CDATA["+ sessionid +"]]></ref_id>\r\n");
				buffer.append("<action_prfrm><![CDATA[Login]]></action_prfrm>\r\n");
				buffer.append("<action_status><![CDATA["+loginstatus+"]]></action_status>\r\n");
				buffer.append("<chg_term><![CDATA["+chgterm+"]]></chg_term>\r\n");
				buffer.append("<tran_id><![CDATA["+sessionid+"]]></tran_id> \r\n");
				buffer.append("<chg_user><![CDATA["+userId+"]]></chg_user> \r\n");
				buffer.append("<chg_date><![CDATA["+newDate+"]]></chg_date> \r\n");
				buffer.append("<descr><![CDATA[Login Session Info]]></descr> \r\n"); // check for this value in cdata
				buffer.append("</Detail1> \r\n");
				
				
				BaseLogger.log("3", userInfo, null, "DFQ before if (logouttime.trim)");
				if((genericUtility.checkNull(logoutTime) != ""))
				{
					
					
					buffer.append("<Detail1 dbID='' domID='" + dom + "' objName='user_audit_trail' objContext='1'>\r\n");
					buffer.append("<attribute pkNames='' status='O' updateFlag='N' selected='N' />\r\n");
					buffer.append("<chg_id><![CDATA[2]]></chg_id>\r\n");
					buffer.append("<obj_name><![CDATA[Logout Session Info]]></obj_name>\r\n");
					buffer.append("<ref_id><![CDATA["+ sessionid +"]]></ref_id>\r\n");
					buffer.append("<action_prfrm><![CDATA[Logout]]></action_prfrm>\r\n");
					buffer.append("<action_status><![CDATA["+loginstatus+"]]></action_status>\r\n");
					buffer.append("<chg_term><![CDATA["+chgterm+"]]></chg_term>\r\n");
					buffer.append("<tran_id><![CDATA["+sessionid+"]]></tran_id> \r\n");
					buffer.append("<chg_user><![CDATA["+userId+"]]></chg_user> \r\n");
					buffer.append("<chg_date><![CDATA["+logoutTime+"]]></chg_date> \r\n");
					buffer.append("<descr><![CDATA[Logout Session Info]]></descr> \r\n"); // check for this value in cdata
					buffer.append("</Detail1> \r\n");
					
				}
				
				xmlbufferdata = buffer.toString();
				dom++;
				
				
				BaseLogger.log("3", userInfo, null, "DFQ domm:" + dom);

			}

		}

		catch (Exception e) {

			e.printStackTrace();
			System.out.println("Exception is" + e);
			

		}

		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}

			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}

			if (con != null) {
				con.close();
				con = null;
			}

		}

		catch (SQLException e) {

			e.printStackTrace();
			System.out.println("Exception is:" + e);

		}

		return xmlbufferdata;

	}
	
	public String newDateFormat(String logintime) throws ParseException
	{
		
		BaseLogger.log("3", userInfo, null, "DFQ OLd date format" + logintime);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date newdate = sdf.parse(logintime);
		
		BaseLogger.log("3", userInfo, null, "DFQ NEWDATE" + newdate);

		SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
	
		String finaldate = sdf2.format(newdate);
		System.out.println();
		BaseLogger.log("3", userInfo, null, "DFQ finaldate:  "+finaldate);


		return finaldate;
	}
	
	public String newDateFormatLogoutTime(String logintime) throws ParseException
	{
		
		BaseLogger.log("3", userInfo, null, "DFQ OLd date format" + logintime);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date newdate = sdf.parse(logintime);
		
		BaseLogger.log("3", userInfo, null, "DFQ NEWDATE" + newdate);

		SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
	
		String finaldate = sdf2.format(newdate);
		System.out.println();
		BaseLogger.log("3", userInfo, null, "DFQ finaldate:  "+finaldate);


		return finaldate;
	}
	

}
