<%@ page language="java"
    contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="java.util.*"
    import="java.io.*"
    import="java.text.SimpleDateFormat"
    import="java.text.NumberFormat"
    import="java.math.BigDecimal"
    import="java.net.URLEncoder"
    import="com.gridnine.xtrip.common.Environment"
    import="com.gridnine.xtrip.common.util.TextUtil"
    import="com.gridnine.xtrip.server.gds.GDSStatistics"
    import="com.gridnine.xtrip.common.model.profile.Organization"
	import="com.gridnine.xtrip.common.model.profile.OrganizationIndex"
	import="com.gridnine.xtrip.common.model.EntityCache"
	import="com.gridnine.xtrip.common.model.EntityContainer"
	import="com.gridnine.xtrip.common.model.profile.Organization"
	import="com.gridnine.xtrip.common.model.profile.OrganizationIndex"
	import="com.gridnine.xtrip.common.util.CollectionUtil"
%>

<%@page %>

<%@page import="com.gridnine.xtrip.common.model.dict.GdsName"%><html><head><title>Статистика по запросам</title>
<script language="JavaScript">
	function showDetails(gdsName, partnerId) {
		var popupWnd=window.open('details.jsp?gds='+gdsName+'&partnerId='+encodeURIComponent(partnerId),'Details','width=450,height=320,top=120,left=120,scrollbars=yes,resizable=yes');
		popupWnd.focus();
	}
	function updateStats() {
		var validDateFormat = /^\d{4}-\d{1,2}-\d{1,2}$/;
		if (document.getElementById('from').value!='' && !document.getElementById('from').value.match(validDateFormat)) {
			alert('Invalid date format (must be yyyy-MM-dd)');
			document.getElementById('from').focus();
			return false;
		}
		if (document.getElementById('to').value!='' && !document.getElementById('to').value.match(validDateFormat)) {
			alert('Invalid date format (must be yyyy-MM-dd)');
			document.getElementById('to').focus();
			return false;
		}
		//document.location.reload();
	}
	function clearDates() {
		document.getElementById('from').value="";
		document.getElementById('to').value="";
	}
	</script></head>
	<%
		request.getSession().removeAttribute("requestCountSIRENA");
		request.getSession().removeAttribute("totalPriceSIRENA");
		request.getSession().removeAttribute("logsByPartnerSIRENA");
		request.getSession().removeAttribute("configFileSIRENA");
		request.getSession().removeAttribute("requestCountSABRE");
		request.getSession().removeAttribute("totalPriceSABRE");
		request.getSession().removeAttribute("logsByPartnerSABRE");
		request.getSession().removeAttribute("configFileSABRE");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires",-1);
		Properties configFileSIRENA = new Properties();
		Map<String,BigDecimal> requestCountSIRENA = new HashMap<String,BigDecimal>();
		Map<String,BigDecimal> totalPriceSIRENA = new HashMap<String,BigDecimal>();
		Map<String,List<String>> logsByPartnerSIRENA = new HashMap<String,List<String>>();
		Properties configFileSABRE = new Properties();
		Map<String,BigDecimal> requestCountSABRE = new HashMap<String,BigDecimal>();
		Map<String,BigDecimal> totalPriceSABRE = new HashMap<String,BigDecimal>();
		Map<String,List<String>> logsByPartnerSABRE = new HashMap<String,List<String>>();
		SimpleDateFormat periodDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		if ("true".equals(request.getParameter("showStats"))) {
			// SIRENA!!!
		    File file =
	            new File(Environment.getConfigurationFolder(),"stats_sirena.properties");
	        if (file.isFile()) {
	            try {
	                InputStream strm = new FileInputStream(file);
	                try {
	                    configFileSIRENA.load(strm);
	                } finally {
	                    strm.close();
	                }
	            } catch (Exception e) {
	            	%><p>"error while parsing sirena properties file!"</p><%
	                //   LOG.error("failed loading configuration from file " + file, e); //$NON-NLS-1$
	            }
	        } else {
	        	%><p>"sirena properties file not found!"</p><%
	            // LOG.error("configuration file not found " + file); //$NON-NLS-1$
	        }
	     // SABRE!!!
		    File fileSABRE =
	            new File(Environment.getConfigurationFolder(),"stats_sabre.properties");
	        if (fileSABRE.isFile()) {
	            try {
	                InputStream strm = new FileInputStream(fileSABRE);
	                try {
	                    configFileSABRE.load(strm);
	                } finally {
	                    strm.close();
	                }
	            } catch (Exception e) {
	            	%><p>"error while parsing sabre properties file!"</p><%
	                //   LOG.error("failed loading configuration from file " + file, e); //$NON-NLS-1$
	            }
	        } else {
	        	%><p>"sabre properties file not found!"</p><%
	            // LOG.error("configuration file not found " + file); //$NON-NLS-1$
	        }
	        File logsDir =
	            new File(System.getProperty("user.dir")
	                + "/logs/stat");
	        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS", Locale.getDefault());
	        Date from = !TextUtil.isBlank(request.getParameter("from")) ? periodDateFormat.parse(request.getParameter("from")) : null;
	        Date to = !TextUtil.isBlank(request.getParameter("to")) ? new Date(periodDateFormat.parse(request.getParameter("to")).getTime() + 24 * 60 * 60 * 1000L) : null;
	        for (File logFile : logsDir.listFiles()) {
	            BufferedReader logFileBF =
	                new BufferedReader(new FileReader(logFile));
	            try
	            {
	            	String entry;
	            	while ((entry = logFileBF.readLine()) != null) {
	            		try
	            		{
		            		String[] parts = entry.split("\\|");
			   				 Date time = dtf.parse(parts[0]);
			   				 if (from != null && from.after(time))
			   					 continue;
			   				 if (to != null && to.before(time)) {
			   					 continue;
			   				 }
			   				 GdsName gds = CollectionUtil.findEnumConstant(
			   			                GdsName.class, parts[1]);
			   				 String partnerId;
			   				 if (gds != null)
			   				 {
				   				 switch (gds)
				   				 {
				   				 case SIRENA:
				   					partnerId = parts[9];
					   				 if (requestCountSIRENA.get(partnerId)==null) {
					   					 requestCountSIRENA.put(partnerId,BigDecimal.ZERO);
					   				 }
					   				 requestCountSIRENA.put(partnerId,requestCountSIRENA.get(partnerId).add(BigDecimal.ONE));

					   				 if (totalPriceSIRENA.get(partnerId)==null) {
					   					 totalPriceSIRENA.put(partnerId,BigDecimal.ZERO);
					   				 }
					   				 try {
					   				 	totalPriceSIRENA.put(partnerId,totalPriceSIRENA.get(partnerId).add(new BigDecimal(configFileSIRENA.getProperty(parts[10]))));
					   				 } catch (Throwable t) {
					   		              // LOG.error("Cannot get price for query: " + query);
					   			           //   return 0;
					   		          }

					   				 if (logsByPartnerSIRENA.get(partnerId)==null) {
					   					 logsByPartnerSIRENA.put(partnerId,new LinkedList<String>());
					   				 }
					   				 logsByPartnerSIRENA.get(partnerId).add(entry);
				   					 break;
				   				 case SABRE:
				   					partnerId = parts[9];
					   				 if (requestCountSABRE.get(partnerId)==null) {
					   					 requestCountSABRE.put(partnerId,BigDecimal.ZERO);
					   				 }
					   				 requestCountSABRE.put(partnerId,requestCountSABRE.get(partnerId).add(BigDecimal.ONE));

					   				 if (totalPriceSABRE.get(partnerId)==null) {
					   					 totalPriceSABRE.put(partnerId,BigDecimal.ZERO);
					   				 }
					   				 try {
					   					 Calendar c = Calendar.getInstance();
					   					 c.setTime(time);
					   					 String time_of_day;
					   					 if ((c.get(Calendar.HOUR_OF_DAY)>=1) && (c.get(Calendar.HOUR_OF_DAY)<18)) {
					   						 time_of_day="_day";
					   					 } else {
					   						 time_of_day="_night";
					   					 }
					   				 	 totalPriceSABRE.put(partnerId,totalPriceSABRE.get(partnerId).add(new BigDecimal(configFileSABRE.getProperty(parts[10]+time_of_day))));
					   				 } catch (Throwable t) {
					   		              // LOG.error("Cannot get price for query: " + query);
					   			           //   return 0;
					   		          }

					   				 if (logsByPartnerSABRE.get(partnerId)==null) {
					   					 logsByPartnerSABRE.put(partnerId,new LinkedList<String>());
					   				 }
					   				 logsByPartnerSABRE.get(partnerId).add(entry);
				   					 break;
				   				 }
			   				 }
	            		}
	            		catch (Exception ex)
	            		{
	            			//out.write("skipped entry: " + entry + " because of exception: " + ex.getMessage());
	            		}
		            }
	            }
	            finally
	            {
	            	logFileBF.close();
	            }
	        }
			request.getSession().setAttribute("requestCountSIRENA",requestCountSIRENA);
			request.getSession().setAttribute("totalPriceSIRENA",totalPriceSIRENA);
			request.getSession().setAttribute("logsByPartnerSIRENA",logsByPartnerSIRENA);
			request.getSession().setAttribute("configFileSIRENA",configFileSIRENA);
			request.getSession().removeAttribute("from");

			request.getSession().setAttribute("requestCountSABRE",requestCountSABRE);
			request.getSession().setAttribute("totalPriceSABRE",totalPriceSABRE);
			request.getSession().setAttribute("logsByPartnerSABRE",logsByPartnerSABRE);
			request.getSession().setAttribute("configFileSABRE",configFileSABRE);
			request.getSession().removeAttribute("from");

			if (!TextUtil.isBlank(request.getParameter("from"))) {
				request.getSession().setAttribute("from",request.getParameter("from"));
			}
			request.getSession().removeAttribute("to");
			if (!TextUtil.isBlank(request.getParameter("to"))) {
				request.getSession().setAttribute("to",request.getParameter("to"));
			}
		}
	%>
<body>
<form action="" onsubmit="return updateStats()">
<input type="submit" value="Показать всю статистику" onclick="javascript:clearDates()"/>
<p>Дата начала отчетного периода (yyyy-MM-dd): <input type="text" alt="yyyy-MM-dd" name="from" id="from" size="10" value="<%=(request.getParameter("from")!=null)?request.getParameter("from"):"" %>"/> Дата окончания отчетного периода (yyyy-MM-dd): <input type="text" alt="yyyy-MM-dd" name="to" id="to" size="10" value="<%=(request.getParameter("to")!=null)?request.getParameter("to"):"" %>" /> <input type="submit" value="Обновить"/></p>
<p>Статистика по GDS SIRENA</p>
<table border="1">
   	<tr><th>Партнер</th><th>Всего запросов</th><th>Сумма баллов</th><th></th></tr>
    <%
        for(String partnerId : requestCountSIRENA.keySet()) {
    	    	String partnerName=partnerId;
        		EntityContainer<Organization> sa = Environment.getPublished(EntityStorage.class).find(OrganizationIndex.class, OrganizationIndex.Property.code.name(), partnerId);
        		if (sa!=null && sa.getEntity()!=null) {
        	partnerName = sa.getEntity().getCode()+"|"+sa.getEntity().getShortName()+"|"+sa.getEntity().getFullName();
        }
        if (TextUtil.isBlank(partnerName) || "||".equalsIgnoreCase(partnerName)) {
        	continue;
        }
    %><tr>
    	    <td><%=partnerName%></td>
        	<td><%=requestCountSIRENA.get(partnerId).intValue()%></td>
            <td><%=totalPriceSIRENA.get(partnerId).intValue()%></td>
            <td><a href="javascript:showDetails('<%=GdsName.SIRENA.name()%>','<%=partnerId%>')">Детализация</a></td>
        <%
            }
        %>
</table>
<br/>
<p>Статистика по GDS SABRE</p>
<table border="1">
   	<tr><th>Партнер</th><th>Всего запросов</th><th>Сумма центов</th><th></th></tr>
    <%
        for(String partnerId : requestCountSABRE.keySet()) {
    	    	String partnerName=partnerId;
        		EntityContainer<Organization> sa = Environment.getPublished(EntityStorage.class).find(OrganizationIndex.class, OrganizationIndex.Property.code.name(), partnerId);
        if (sa!=null && sa.getEntity()!=null) {
        	partnerName = sa.getEntity().getCode()+"|"+sa.getEntity().getShortName()+"|"+sa.getEntity().getFullName();
        }
        if (TextUtil.isBlank(partnerName) || "||".equalsIgnoreCase(partnerName)) {
        	continue;
        }
    %><tr>
    	    <td><%=partnerName %></td>
        	<td><%=requestCountSABRE.get(partnerId).intValue() %></td>
        	<% NumberFormat f = NumberFormat.getInstance();
			   f.setGroupingUsed(false);
			   f.setMinimumFractionDigits(5);
			   BigDecimal value = totalPriceSABRE.get(partnerId);%>
            <td><%=f.format(value) %></td>
            <td><a href="javascript:showDetails('<%=GdsName.SABRE.name() %>','<%= partnerId %>')">Детализация</a></td>
        <% } %>
</table>
<input type="hidden" name="showStats" value="true"/>
</form>
</body>
</html>
<% out.close();
System.gc();
%>