<%@page import="ibase.webitm.ejb.ITMUserAuditBrowFormEJB"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.stream.StreamSource"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="org.apache.poi.ss.usermodel.DataFormat"%>
<%@page import="ibase.utility.E12GenericUtility"%>
<%@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"/>
<jsp:useBean id="itmuserauditbeantest" class="ibase.webitm.bean.ITMUserAuditBeanTest"/>

<%@page import="ibase.utility.BaseLogger"%>
<%! ibase.utility.UserInfoBean userInfo = null; %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page buffer = "2048kb" autoFlush = "true" %>


<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>
<%
	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 formatter3 = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
		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, "dfq inside html if case");
			dataNew = auditBean.getXMLStrBrow("EXCELDATA");
			BaseLogger.log("3",userInfo,null, "datanew daniel in html from auditbean.getxmlstrbrow"+dataNew);

			
			boolean noDataCheck = dataNew.contains("<nodata>");
			BaseLogger.log("3",userInfo,null, "daniel nodatacheckvalue"+noDataCheck);
			
			if(noDataCheck)
			{
				String tagtoremove = "nodata";
				BaseLogger.log("3",userInfo,null, "daniel tagtoremove"+tagtoremove);
				dataNew = dataNew.replaceAll("<" + tagtoremove + ">.*?</" + tagtoremove + ">", "");
				BaseLogger.log("3",userInfo,null, "daniel datanew after removing <nodata> tag"+dataNew);

				String closingtags =  "</Header0>"+"\r\n"+"</group0> "+"\r\n"+"</DocumentRoot>" ;
				dataNew = dataNew.replaceAll("</DocumentRoot>", "");
				dataNew = dataNew.replaceAll("</Header0>", "");
				dataNew = dataNew.replaceAll("</group0>", "");
				BaseLogger.log("3",userInfo,null, "datanew daniel after remove closing tags in if nodatacheck in html"+dataNew);
				String xmlFrNoRecords = "<Detail1 dbID='' domID='' objName='' objContext=''> <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> </Detail1>";
				sessiondata=itmuserauditbeantest.getSessionInfoDet(userStr, fromDateformat, toDateformat);			
				dataNew = dataNew+sessiondata+xmlFrNoRecords+closingtags;

				//can be added in a method and returning data to be stored in datanew datanew = handleNoDataXml.

			}
			
			//else { add the below code inside this else add below 10 lines in here }
			else {
				
				dataNew = dataNew.replaceAll("</DocumentRoot>", "");
				dataNew = dataNew.replaceAll("</Header0>", "");
				dataNew = dataNew.replaceAll("</group0>", "");
				BaseLogger.log("3",userInfo,null, "datanew daniel after remove closing tags in else sectio html"+dataNew);

				sessiondata=itmuserauditbeantest.getSessionInfoDet(userStr, fromDateformat, toDateformat);			
				BaseLogger.log("3",userInfo,null, "sessiondata daniel in html"+sessiondata);

				
				String xmlstrg = "<?xml version='1.0' encoding='UTF-8'?>" +"\r\n"+"<DocumentRoot>"+"\r\n" + "<description>Datawindow Root</description>"+ "\r\n"+ "<group0>"+"\r\n" + "<description>Group0 description</description>"+"\r\n" +"<Header0>"+"\r\n" +"<description>Header0 members</description>";
				String closingtags =  "</Header0>"+"\r\n"+"</group0> "+"\r\n"+"</DocumentRoot>" ;
				dataNew =dataNew+sessiondata+closingtags;
				//dataNew = dataNew+sessiondata+xmlFrNoRecords+closingtags;
				BaseLogger.log("3",userInfo,null, "finaldata of datanew daniel  FOR HTML with start & close tags"+dataNew);
				
				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(dataNew)), new StreamResult(bos));
			        dataNew = bos.toString();
					BaseLogger.log("3",userInfo,null, "daniel final datanew converted into html data"+dataNew);

				}
				
				catch (Exception e) {
					
					e.printStackTrace();
					BaseLogger.log("3",userInfo,null, "daniel Exception is:::");
				}
				
				
				BaseLogger.log("3",userInfo,null, "dataNew gsb :");
				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 after removing closing tags daniel "+dataNew);

			BaseLogger.log("3",userInfo,null, "todate daniel "+toDateformat);
			BaseLogger.log("3",userInfo,null, "frdate daniel "+fromDateformat);
			BaseLogger.log("3",userInfo,null, "userStr daniel "+userStr);

			
			sessiondata=itmuserauditbeantest.getSessionInfoDet(userStr, fromDateformat, toDateformat);
			BaseLogger.log("3",userInfo,null, "daniel sessiondataa in excel :: "+sessiondata);
			
		    String xmlstrg = "<?xml version='1.0' encoding='UTF-8'?>" +"\r\n"+"<DocumentRoot>"+"\r\n" + "<description>Datawindow Root</description>"+ "\r\n"+ "<group0>"+"\r\n" + "<description>Group0 description</description>"+"\r\n" +"<Header0>"+"\r\n" +"<description>Header0 members</description>";
			String closingtags ="</Header0>"+"\r\n"+"</group0>"+"\r\n"+"</DocumentRoot>";

			dataNew =dataNew+sessiondata  +closingtags;
			BaseLogger.log("3",userInfo,null, "finaldata of datanew for excel daniel end of code "+dataNew);
			
			XLSWriter export2xls1 = new XLSWriter();
	        HSSFWorkbook workBook = export2xls1.exportToExcelFile(dataNew);
			 
	        BaseLogger.log("3",userInfo,null, "Below HSSFworkbook daniel end of code ");

	        response.setContentType("application/vnd.ms-excel");
	        response.setHeader("Content-disposition", "filename=" +"userAuditTrail" + System.currentTimeMillis()  + ".xls" );
	        OutputStream out1 = response.getOutputStream();
	        BaseLogger.log("3",userInfo,null, "Below OutputStream out1 daniel");
			boolean responsecommitstatus =  response.isCommitted();
	        BaseLogger.log("3",userInfo,null, "To check response commit response DANIEL responsecommitstatus: "+responsecommitstatus);

	        workBook.write(out1);
	        BaseLogger.log("3",userInfo,null, "under workBook.write(out1) daniel "+workBook);
	        out1.flush();
	        out1.close();
	        
	        BaseLogger.log("3",userInfo,null, "after out1.close daniel before return");

	        
        	return;
		}        	
	}
	
	catch(Exception e){
		BaseLogger.log("0",userInfo,null, "Inside ITMAuditBrow");
	   e.printStackTrace();
	}
	%>
<%! 
    String dataNew = ""; 
    String fromDateformat = "";
    String toDateformat = "";
    String selectValData = "";
    String sessiondata = "";
    Date frdate = null;
    Date todate = null;
    Date fromDateFormat = null;
    Date toDateFormat = null;
    String sessiondataa = "";
    String fromDateTimeFormat = "";
    String toDateTimeFormat = "";
	String objName = "user_audit_trail";
	String objContext = "1";
	String pContext = "1";
		ITMUserAuditBeanTest itmuser = new ITMUserAuditBeanTest();
    
	private String checkNull(String input) 
	{
	
		if (input == null) 
		{
			input = "";
		}
		
		else 
		{
			input = input.trim();
		}
		return input.trim();
	
	}
	
	//changes by daniel : END
	%>
<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">
			<%= dataNew %>
			</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>