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);
			BaseLogger.log("2", userInfo, null," Retdatanotfound value:::"+retData);

			
			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) {

		String sessionid = "", chg_user = "", loginstatus = "", chgterm = "", chguser = "", logintime = "",
				xmlbufferdata = "", logoutTime = "" , newDtFOrmatlogoutTime="",newDate = "";
		Timestamp loginTime = null;
		java.sql.PreparedStatement pstmt = null;
		Connection con = null;
		ResultSet rs = null;
		Date datee,logouTTime= null;
		Timestamp fromdate = null, todate = null, newLoginTIme = null;
		int dom = 1000;
		
		
		BaseLogger.log("3", null, null, "Userid::"+userId);
		BaseLogger.log("3", null, null, "Fromdate::"+fromDate);
		BaseLogger.log("3", null, null, "Todate::"+toDate);


		try {
			
			CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
			 userInfo = commonDBAccessEJB.createUserInfo(userId);
			BaseLogger.log("3", userInfo, null, "Userinfo::" + userInfo);
			ValidatorEJB valejb = new ValidatorEJB();
			valejb.setUserInfo(userInfo);
			con = valejb.getConnection();

			BaseLogger.log("3", userInfo, null, "Fromdate:" + fromDate);
			BaseLogger.log("3", userInfo, null, "Todate::" + toDate);

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

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

			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 = (rs.getTimestamp("LOGINTIME")) ;
				chg_user = genericUtility.checkNull(rs.getString("USERID"));
				logoutTime = genericUtility.checkNull(rs.getString("LOGOUTTIME"));

				BaseLogger.log("3", userInfo, null, "Sessionid::" + sessionid);
				BaseLogger.log("3", userInfo, null, "Loginstatus::" + loginstatus);
				BaseLogger.log("3", userInfo, null, "Chgterm" + chgterm);
				BaseLogger.log("3", userInfo, null, "Chguser::" + chguser);
				BaseLogger.log("3", userInfo, null, "Logintime::" + loginTime);
				BaseLogger.log("3", userInfo, null, "Str logouTime::" + logoutTime);

				newDate = newDateFormat(loginTime);
				BaseLogger.log("3", userInfo, null, "Newdate from newdateformat method" + newDate);	

				
				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"); 
				buffer.append("</Detail1> \r\n");
				
				
				if((genericUtility.checkNull(logoutTime) != ""))
				{
					
					dom++;
					BaseLogger.log("3", userInfo, null, " Logout sessionid::" + sessionid);
					BaseLogger.log("3", userInfo, null, " Logout loginstatus::" + loginstatus);
					BaseLogger.log("3", userInfo, null, " Logout chgterm" + chgterm);
					BaseLogger.log("3", userInfo, null, " Logout chguser::" + chguser);
					BaseLogger.log("3", userInfo, null, " Logout str logoutTime::" + logoutTime);

					newDtFOrmatlogoutTime = newDateFormatLogoutTime(logoutTime);
					BaseLogger.log("3", userInfo, null, "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[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["+newDtFOrmatlogoutTime+"]]></chg_date> \r\n");
					buffer.append("<descr><![CDATA[Logout Session Info]]></descr> \r\n"); 
					buffer.append("</Detail1> \r\n");
					
				}
				
				xmlbufferdata = buffer.toString();
				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(Timestamp logintime) throws ParseException
	{
		
		BaseLogger.log("3", userInfo, null, "LoginTime" + logintime);
		Date date = new Date(logintime.getTime());
		
		BaseLogger.log("3", userInfo, null, "NEWDATE" + date);

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


		return finaldate;
	}
	
	public String newDateFormatLogoutTime(String logouttime) throws ParseException
	{
		String finaldate = null;
		
		if(logouttime.trim().length() >0 || !logouttime.equalsIgnoreCase("") || !logouttime.equalsIgnoreCase("null"))
		{
			BaseLogger.log("3", userInfo, null, "Logout Time" + logouttime);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date newdate = sdf.parse(logouttime);
			
			BaseLogger.log("3", userInfo, null, "NEWdate" + newdate);

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

			
		}

		return finaldate;
	}
	
	public String hanldeNoDataXml(String datanew)
	
	{
		datanew = datanew.replaceAll("</DocumentRoot>", "");
		datanew = datanew.replaceAll("</Header0>", "");
		datanew = datanew.replaceAll("</group0>", "");
		String xmlFrNoRecords = "<Detail1 dbID='' domID='' objName='user_audit_trail' objContext='1'> <attribute pkNames='' status='O' updateFlag='' selected='' /> <chg_id><![CDATA[]]></chg_id> <obj_name><![CDATA[]]></obj_name> <ref_id><![CDATA[]]></ref_id><action_prfrm><![CDATA[]]></action_prfrm><action_status><![CDATA[]]></action_status><chg_term><![CDATA[]]></chg_term><tran_id><![CDATA[]]></tran_id> <chg_user><![CDATA[]]></chg_user> <chg_date><![CDATA[]]></chg_date> <descr><![CDATA[NO RECORDS FOUND FOR AUDIT TRAIL]]></descr> \n</Detail1>";
		
		return "";
	}

}
