package ibase.webitm.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

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 org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ibase.system.config.AppConnectParm;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.ITMBrowFormEJB;
import ibase.webitm.ejb.ITMUserAuditBrowFormEJB;
import ibase.webitm.utility.I18NLabel;
import ibase.webitm.utility.ITMException;

public class ITMUserAuditBean 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;
		}
		
		
		
		//changes by daniel : START
		
		public String getSessionInfoDet(String userId,String fromDate,String toDate) throws SQLException
		{		
			
			String sessionid = "",chg_user = "", loginstatus= "", chgterm = "", chguser = "", logintime = "", xmlbufferdata = "";
			java.sql.PreparedStatement pstmt = null;
			Connection con = null;
			ResultSet rs = null;
			DateFormat dateformat,dateformat2;
			Date datee;
			Timestamp fromdate = null, todate = null;
			int dom = 1000;
			
			try {
				
				ActionHandlerEJB action = new ActionHandlerEJB();
				con = action.getConnection();
				UserInfoBean userinfo = action.getUserInfo();
			
				BaseLogger.log("3",userinfo,null,"DANIel fromdate:"+fromDate);
				BaseLogger.log("3",userinfo,null,"DANIel todate::"+toDate);

//				 fromdate = Timestamp.valueOf(fromDate);
//				 todate = Timestamp.valueOf(toDate);
				
				String sql = "SELECT * FROM LOGINTRACE WHERE LOGIN_STATUS = 'T' AND USERID = ? AND LOGINTIME >= ? AND TRUNC(LOGINTIME) <= ?"		;
				BaseLogger.log("3",userinfo,null,"DANIel result from sql::"+sql);

				
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, userId);
				pstmt.setString(2, fromDate);
				pstmt.setString(3, toDate);
				
//				if timestamp is needed instead of String			
//				pstmt.setTimestamp(2, fromdate);
//				pstmt.setTimestamp(3, todate);
				
				rs =  pstmt.executeQuery();
				
				 StringBuffer buffer = new StringBuffer();
				 
				while(rs.next())
				{
					
					 sessionid = checkNull(rs.getString("SESSIONID"));
					 loginstatus = checkNull(rs.getString("LOGIN_STATUS"));
					 chgterm = checkNull(rs.getString("CHG_TERM"));
					 logintime = checkNull(rs.getString("LOGINTIME"));
					 chg_user = checkNull(rs.getString("USERID")) ;

					 
						BaseLogger.log("3",userinfo,null,"DANIel sessionid::"+sessionid);
						BaseLogger.log("3",userinfo,null,"DANIel loginstatus::"+loginstatus);
						BaseLogger.log("3",userinfo,null,"DANIel chgterm"+chgterm);
						BaseLogger.log("3",userinfo,null,"DANIel chguser::"+chguser);
						BaseLogger.log("3",userinfo,null,"DANIel logintime::"+logintime);


						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['"+logintime+"']]></chg_date> \r\n");
						buffer.append("<descr><![CDATA[Credit Note]]></descr> \r\n"); //check for this value in cdata
						buffer.append("</Detail1> \r\n");
						buffer.append("</DocumentRoot> \r\n");
						
						xmlbufferdata = buffer.toString();
					 	dom++;
						BaseLogger.log("3",userinfo,null,"DANIel domm:"+dom);

				}
			}
			
			catch (Exception e)
			{
				
			e.printStackTrace();
			System.out.println("Exception is"+e);
			BaseLogger.log("3",null,null,"DANIel exception is:"+dom);

			}
			
			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;
			
		}

		
		private String checkNull(String input) 
		{
			if (input == null) 
			{
				input = "";
			}
			
			else 
			{
				input = input.trim();
			}
			return input.trim();
		
		}
		
		//changes by daniel : END

}
