<%@page import="ibase.ejb.CommonDBAccessEJB"%>
<%@page import="ibase.webitm.ejb.ValidatorEJB"%>
<%@page import="ibase.system.config.ConnDriver"%>
<%@page import="ibase.webitm.ejb.ActionHandlerEJB"%>
<%@page import="cdjd.com.google.protobuf.Timestamp"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%BaseLogger.log("1",userInfo,null, "\t\tXXXXXXXXXXXXXXX  ITMUserAuditBrow.jsp  XXXXXXXXXXXXXXXXXXXX");%>
<%@page import="org.apache.poi.hssf.usermodel.*"%>
<%@page import="ibase.webitm.bean.*, ibase.utility.UserInfoBean"%> 
<%@page import="java.util.Date,java.util.*, java.util.zip.* , java.io.*,javax.xml.transform.*, java.text.SimpleDateFormat"%>
<%@page import = "ibase.webitm.utility.*, ibase.utility.CommonConstants"%>
<jsp:useBean id="auditBean" class="ibase.webitm.bean.ITMUserAuditBean"/>
<%@page import="ibase.utility.BaseLogger"%>
<%! ibase.utility.UserInfoBean userInfo = null; %>

<SCRIPT language="JAVASCRIPT">
function alertUser(){
	alert("Please enter valid SiteCode");
	window.opener.parent.location.href = "../../jsp/login.jsp";
	window.close();
}
function noDataAlert() {
    alert("No Data Found.");
    localStorage.setItem('user_audit_remove_item',true);
    history.back();
    //document.location = '/ibase/webitm/jsp/ITMUserAuditTrailArguement.jsp';
}
function showPreviousPage(){
    localStorage.setItem('user_audit_remove_item',true);
    history.back();
    //document.location = '/ibase/webitm/jsp/ITMUserAuditTrailArguement.jsp';
}
</SCRIPT>

<%! 
    String dataNew = ""; 
    String fromDateformat = "";
    String toDateformat = "";
    String selectValData = "";
    String sessiondata = "";
    Date frdate = null;
    Date todate = null;
 
	public String getSessionInfoDet(String userId,String fromDate,String toDate) throws SQLException
	{		
	
		BaseLogger.log("3",null,null,"DANIEL Inside getSessionInfoDet::");

		String sessionid = "",chg_user = "", loginstatus= "", chgterm = "", chguser = "", logintime = "", xmlbufferdata = "";
		java.sql.PreparedStatement pstmt = null;
		Connection con = null;
		ResultSet rs = null;
//		DateFormatBean dateformat,dateformat2;
		Date datee;
		Timestamp fromdate = null, todate = null;
		int dom = 1000;
		
		BaseLogger.log("3",null,null,"DANIEL after variables before try::");

		
		try {
			BaseLogger.log("3",null,null,"DANIEL firstline inside try::");
		//	UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
			CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
			UserInfoBean userinfo =commonDBAccessEJB.createUserInfo(userId);
			BaseLogger.log("3",userinfo,null,"DANIEL below userinfo creation::"+userinfo);
		//	ActionHandlerEJB action = new ActionHandlerEJB();
			ValidatorEJB valejb = new ValidatorEJB();
			valejb.setUserInfo(userInfo);
			con = valejb.getConnection();
			// UserInfoBean userinfo = action.getUserInfo();
			//con = action.getConnection();
			//ConnDriver conndriver = new ConnDriver();
			//con = conndriver.getConnectDB("Driver");
			BaseLogger.log("3",userinfo,null,"DANIEL below action.getconnection con::"+con);

		
			BaseLogger.log("3",userinfo,null,"DANIel fromdate:"+fromDate);
			BaseLogger.log("3",userinfo,null,"DANIel todate::"+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);
			
			rs =  pstmt.executeQuery();
			
			BaseLogger.log("3",userinfo,null,"DANIel below resultset::"+rs);

					
			 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");

					xmlbufferdata = buffer.toString();
				 	dom++;
					BaseLogger.log("3",userinfo,null,"DANIel 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;
		
	}

	private String checkNull(String input) 
	{
	
	

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




<%
	CommonConstants.setIBASEHOME();
	userInfo = null;
	String theme = "", uxInterface = "", displayThemeXSL = "";
	
	try{
		userInfo = ( ibase.utility.UserInfoBean )session.getAttribute( "USER_INFO" );
		String userStr = request.getParameter("USER");//prerna 26/07/2006 start
		
		if( userStr == null && userInfo == null ){
			BaseLogger.log("3",userInfo,null, "[Forwarding to DirectAccess.jsp from ITMAuditBrow.jsp ..........");
			String directAccessPathStr = ".." + File.separator + ".." + File.separator + "jsp" + File.separator + "DirectAccess.jsp";
%>	
			<jsp:forward page="<%= directAccessPathStr%>"/>            
<%
		}
		theme = userInfo.getUserTheme().trim() + "-theme";
		uxInterface = userInfo.getUxInterface().trim();
		
		ibase.utility.E12GenericUtility genericUtility = new ibase.utility.E12GenericUtility();
		displayThemeXSL = session.getAttribute("DISPLAY_THEME") == null ? genericUtility.getThemeFormat() : (String) session.getAttribute("DISPLAY_THEME");

		String sep = "=";
		
		String[] userCodeArr = null;
		userCodeArr = new String[2];
		userCodeArr[0] = request.getParameter("USER");
		auditBean.setUserInfo(userInfo);		

		String loginUserCode = userInfo.getLoginCode();		
		BaseLogger.log("3",userInfo,null, "2-----------loginUserCode=["+loginUserCode+"]");	 

		StringBuffer reqParamBuff = new StringBuffer();
		Enumeration enumNames = request.getParameterNames();
		
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");//yyyy-MM-dd
        SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MMM-yyyy");//yyyy-MM-dd
		SimpleDateFormat formatter = new SimpleDateFormat(genericUtility.getApplDateFormat()); 

		while(enumNames.hasMoreElements()){
			String paramName = (String)enumNames.nextElement();
			String paramvalue = request.getParameter(paramName);

			BaseLogger.log("3",userInfo,null,  "paramName ["+paramName+"] \n paramvalue ["+paramvalue+"]" );
            if ( paramName.equalsIgnoreCase("FROM_DATE") ){
				try {					
					frdate = formatter1.parse(paramvalue);
					BaseLogger.log("3",userInfo,null,"frdate::"+frdate);

                    fromDateformat = formatter2.format(frdate);
                    BaseLogger.log("3",userInfo,null,"fromDateformat::"+fromDateformat);
					
					String fromDateStr = formatter.format(frdate);
					BaseLogger.log("3",userInfo,null,"fromDateStr::"+fromDateStr);
					paramvalue = fromDateStr;					
				}
				catch (Exception ae) {
					ae.printStackTrace();
				}			
			}
			else if ( paramName.equalsIgnoreCase("TO_DATE") ){
				try {					
					todate = formatter1.parse(paramvalue);
					BaseLogger.log("3",userInfo,null,"todate::"+todate);
					
                    toDateformat = formatter2.format(todate);
                    BaseLogger.log("3",userInfo,null,"toDateformat::"+toDateformat);

					String toDateStr = formatter.format(todate);
					BaseLogger.log("3",userInfo,null,"toDateStr::"+toDateStr);
					paramvalue = toDateStr;					
				}
				catch (Exception ae) {
					ae.printStackTrace();
				}
			}
            else if( paramName.equalsIgnoreCase("SELECT_VAL") ){
                selectValData = paramvalue;
            }
            if( ! paramName.equalsIgnoreCase("SELECT_VAL") ){
                reqParamBuff.append(paramvalue).append(sep);
            }			
		}	
		if(reqParamBuff.toString().endsWith(sep)){
			reqParamBuff.deleteCharAt(reqParamBuff.length() - sep.length());
			BaseLogger.log("3",userInfo,null,  "reqParamBuff after removing = ["+reqParamBuff+"] \n " );	
		}        
		BaseLogger.log("3",userInfo,null, "reqParamBuff :["+reqParamBuff.toString()+"]");
		auditBean.setRequestParamStr(reqParamBuff.toString());       
	
		if (selectValData.equalsIgnoreCase("HTML")){
			dataNew = auditBean.getXMLStrBrow("HTML");
			BaseLogger.log("3",userInfo,null, "dataNew gsb :["+dataNew+"]");
			if(dataNew.indexOf("<Detail1")==-1){
			%>	
				<!--script type="text/javascript"> 
					noDataAlert();                
				</script-->             
			<%
			//return;
			}
		}
		else if (selectValData.equalsIgnoreCase("EXCELDATA")){
			//dataNew = auditBean.getXMLStrBrow("EXCELDATA");
		
			
			
			//dataNew = dataNew.replaceAll("</DocumentRoot>", "");
			//dataNew = dataNew.replaceAll("</Header0>", "");
			//dataNew = dataNew.replaceAll("</group0>", "");

			
			
			//BaseLogger.log("3",userInfo,null, "dataNew daniel "+dataNew);
			 sessiondata = getSessionInfoDet("VRS01","01-JAN-21","04-JAN-21");
			BaseLogger.log("3",userInfo,null, "daniel sessiondata :: "+sessiondata );
			//String closingtags = "</DocumentRoot>";
			String closingtags =  "</Header0>"+ "\r\n" + "</group0> " +"\r\n" + "</DocumentRoot>" ;

			//dataNew = dataNew + "\r\n" + sessiondata + "\r\n" +closingtags;
			sessiondata =  sessiondata + "\r\n" +closingtags;
			//BaseLogger.log("3",userInfo,null, "finaldata of datanew daniel end of code "+dataNew);
			BaseLogger.log("3",userInfo,null, "finaldata of datanew daniel end of code "+sessiondata);

			//below to send it with sessiondata
			
			
			XLSWriter export2xls1 = new XLSWriter();
	        HSSFWorkbook workBook = export2xls1.exportToExcelFile(sessiondata);
	        //sessiondata HSSFWorkbook workBook = export2xls1.exportToExcelFile(dataNew); changes also 
			// and changes below for replaced datanew with my sessiondata <div style="overflow-x: hidden; height: 378px; width: 99.2%;" class="listandGridView e12AdvDataGrid-SideBars" id="e12LstViewWidget-feedScrollPnl">
			//<%= dataNew % > </div>
			 
	        
	        response.setContentType("application/vnd.ms-excel");
	        response.setHeader("Content-disposition", "filename=" +"userAuditTrail" + System.currentTimeMillis()  + ".xls" );
	        OutputStream out1 = response.getOutputStream();
	        workBook.write(out1);
	        out1.flush();
	        out1.close();
        	return;
		}        	
	}
	catch(Exception e){
		BaseLogger.log("0",userInfo,null, "Inside ITMAuditBrow");
	   e.printStackTrace();
	}
	
	
	%>
	
	
	
	


<html>
	<head>
		<title>Audit Trail Detail</title>
		<%-- Changed by Sneha on 28-11-2016, to get themes [Start] --%>
		<link type="text/css" rel="stylesheet" href="/ibase/webitm/css/default.css"/>
 		<link type="text/css" rel="stylesheet" href="/ibase/webitm/css/<%=uxInterface%>/<%=theme%>.css"/>
		<link type="text/css" rel="stylesheet" href="/ibase/webitm/css/<%=displayThemeXSL%>/default.css"/>  
		<link type="text/css" rel="stylesheet" href="/ibase/webitm/css/ITMAttachmentView.css"/>
		<%-- Changed by Sneha on 28-11-2016, to get themes [End] --%>
	</head>
    <style>
    .submitBtnCss
    {
        border: 1px solid #E7E7E7;
        border-radius: 2px;
        -moz-border-radius: 2px;
        -webkit-border-radius: 2px;
        -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
        -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
        color: #333;
        height: 30px;
        font-family: 'MuseoLight-300', sans-serif;
        font-size: 14px;
        background-color: #e7e7e7;
        cursor: pointer;        
    }
    .divTxtCss
    {
        white-space: normal;
        font-size: 16px;        
        color: #666;
        margin-right: 36px;
    }
    .divFontTxtCss{
        white-space: normal;
        font-size: 16px;        
        color: #666;
    }
    </style>
    <body>

    <table class="flextableTabView" cellspacing="0" cellpadding="0" style="width: 100%;">
	<tr style="height: 32px; vertical-align:middle;">
		<td>
			<table cellspacing="0" cellpadding="0" style="vertical-align: middle;width:calc(100% - 8px);">
				<tr>
					<td align="left" style="vertical-align: middle;">			
						<table cellspacing="0" cellpadding="0">
							<tr>
								<td align="left" style="vertical-align: top;">
									<table cellspacing="0" cellpadding="0" style="margin: 0px 8px;">
										<tr>
											<td align="left" style="vertical-align: top;">
												<div class="divTxtCss">User: <%= request.getParameter("USER")%></div> 
											</td>
											<td style="vertical-align: top;">
												<div class="divTxtCss">From Date: <%= fromDateformat%></div>
											</td>
											<td style="vertical-align: top;">
												<div class="divFontTxtCss">To Date: <%= toDateformat%></div>
											</td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr style="height: calc(100% - 68px);">
		<td>	
			<div style="overflow-x: hidden; height: 378px; width: 99.2%;" class="listandGridView e12AdvDataGrid-SideBars" id="e12LstViewWidget-feedScrollPnl">
			<%= sessiondata %>
			</div>
		</td>	
	</tr>
    <tr style="height: 32px; vertical-align:middle;">
		<td align="left" style="vertical-align: top;">
            <div>
              <input type = button value = "Back" class="submitBtnCss" style="color: #333; margin-top: 10px;" onCLick="showPreviousPage();">    
            </div> 
        </td>	
	</tr>
<table>   
</body>
</html>