<%@page contentType="text/html"%>
<%@page
	import="javax.xml.parsers.DocumentBuilderFactory,javax.xml.parsers.DocumentBuilder,org.w3c.dom.*"%>
<%@page import="ibase.dashboard.mfg.bean.*"%>
<%@page import="javax.naming.Context"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="ibase.webitm.utility.GenericUtility"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.Enumeration"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.text.SimpleDateFormat"%>

<jsp:useBean id="productionVsBudgetBean" scope="request"
	class="ibase.dashboard.mfg.bean.ProductionVsBudgetReportBean" />
<%!GenericUtility genericUtility = GenericUtility.getInstance();
	String objName = "";
	Document dom = null;
	NodeList dtlList = null;
	Node parentNode = null;
	NodeList childNodeList = null;
	Node currDetail = null;
	ArrayList<String> chartDataList = null;
	List<String> geoLocList   = new ArrayList<String>();
	List<String> unitFormList =new ArrayList<String>();
	
	
	String childNodeName = "";
	String period = "";
	String netsales = "";
	String amount = "";
	String fin_entity = "";
	StringBuffer chartData = null;
	String xmlDataString = "";
	String selectedEntity = "";
	String entity = "", descr = "";
	String user = "TA821";
	String rptTitle = "";
	String srcJSPath = "";
	String srcImagesPath = "";
	Calendar calendar = null;
	String frmDate = "";
	String toDate = "";
	String dayQty = "";
	NodeList locationList = null;
	NodeList detailList = null;
	NodeList unitList = null;
	NodeList dateList = null;
	NodeList dayQtyList = null;
	Node locationNode = null;
	NodeList foreCastList = null;
	Node unitNode = null;
	Node dateNode = null;
	Node dayNode = null;
	Node foreCastNode=null;
	String date = "";
	int lastDayOfMonth=0;
	int todaysDay=0;
	SimpleDateFormat simpleDateFormat = null;%>
<%
	response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
	response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	response.setHeader("Pragma", "no-cache");
%>
<%
	String userAgent = request.getHeader("user-agent");
	System.out.println("userAgent ==" + userAgent);
	if (userAgent.indexOf("Android") > 0 || userAgent.indexOf("iPhone") > 0 || userAgent.indexOf("iPad") > 0)
	{
		srcJSPath = "ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "ibase/FusionChart/images/MSCombi3D.swf";

	} else
	{
		srcJSPath = "/ibase/FusionChart/js/FusionCharts.js";
		srcImagesPath = "/ibase/FusionChart/images/MSCombi3D.swf";

		System.out.println("srcJSPath ==" + srcJSPath);
		System.out.println("srcImagesPath ==" + srcImagesPath);

	}
%>

<%@page import="java.util.ArrayList"%><html>
<head>
<style type="text/css">
.tdLabel {
	FONT-FAMILY: Arial;
	font-size: 12pt;
}
</style>
<script type="text/javascript" src="<%=srcJSPath%>"></script>
</head>
<body>

<%
	try
	{

		//ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean) session.getAttribute("USER_INFO");
		//String user  = userInfo.getLoginCode();	
		
		//out.println("user===="+user);		
		simpleDateFormat = new SimpleDateFormat("dd-MMM-yy");
		calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		toDate = simpleDateFormat.format(calendar.getTime());

		
		//out.print("max day ="+calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		//out.print("min day ="+calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		frmDate = simpleDateFormat.format(calendar.getTime());

		 todaysDay     =Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		 		 
		 lastDayOfMonth = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
		
		//frmDate = "01-apr-12";
		//toDate  = "30-apr-12";		
		rptTitle = request.getParameter("rtitle");
		if (rptTitle == null || rptTitle.trim().length() == 0)
		{
			rptTitle = " ";
		} else
		{
			if (rptTitle.equalsIgnoreCase("Y") && rptTitle.trim().length() != 0)
			{
				rptTitle = "Production Vs Budget Report";
			} else
			{
				rptTitle = "";
			}
		}

		if (user != null && user.trim().length() != 0)
		{
			xmlDataString = productionVsBudgetBean.getProductionBudget(frmDate, toDate);
			System.out.print("xmlDataString in jsp= " + xmlDataString);
			
		}
%>
<%
	//Add here Details for Chart container 
       
		dom = genericUtility.parseString(xmlDataString);
       
		if (dom != null)
		{
			chartDataList = new ArrayList<String>();
			detailList  = dom.getElementsByTagName("Detail");
			
			if(detailList.item(0).getFirstChild()!=null)
			{
			locationList  = dom.getElementsByTagName("geo_loc");			
			for (int cntr = 0; cntr < locationList.getLength(); cntr++)
			{
				
				locationNode = locationList.item(cntr);	
				
				
				//Add loc_code in locationList  glocdescr			
				
				geoLocList.add(locationNode.getAttributes().getNamedItem("glocdescr").getNodeValue());						
				chartData = new StringBuffer("<chart caption='");
				chartData.append(rptTitle);
				chartData.append("' palette='1' showValues='0' yAxisValuesPadding='10' numberPrefix='' chartOrder='line,area,column' startAngX='8' startAngY='-32' endAngX='8' endAngY='-32' zdepth='50' zgapPlot='10' showPlotBorder='0' dynamicShading='1' showAlternateHGridColor='1' labelDisplay='Stagger' legendNumColumns='2'>");
				chartData.append("<categories>");

				unitList     = locationNode.getChildNodes();
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{
					
					unitNode = unitList.item(nodCtr);
					
					//Add unit form in unitForm List
					unitFormList.add(unitNode.getAttributes().getNamedItem("unitdescr").getNodeValue());
					//geoLocList.add(locationNode.getAttributes().getNamedItem("glocdescr").getNodeValue());
					
					dateList = unitNode.getChildNodes();
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						
						dateNode = dateList.item(dateCtr);
						date = dateNode.getAttributes().item(0).getNodeValue();
						chartData.append("<category label='" + date + "'/>");
					}
					
				}
				
				
				chartData.append("<category label='" +"fc"+ "'/>");				
				chartData.append("</categories>");
				//5. Start dataset for Forecasting	
				chartData.append("<dataset seriesName='Forecast' >");
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{   
					double cumulativeQty=0.0;
					unitNode = unitList.item(nodCtr);
					dateList = unitNode.getChildNodes();
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						dateNode   = dateList.item(dateCtr);
						dayQtyList = dateNode.getChildNodes();
						int day    =Integer.parseInt(dateNode.getAttributes().item(0).getNodeValue());
						
						for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
						{
							dayNode = dayQtyList.item(dayCtr);
							foreCastList = dayNode.getChildNodes();						 	  
								  
								for (int prevCtr = 0; prevCtr < foreCastList.getLength(); prevCtr++)
								{
									foreCastNode = foreCastList.item(prevCtr);
									
									if(foreCastNode.getNodeName().equals("cur_cumqty"))
									{		
										//out.println("day:"+day+"--todaysDay"+todaysDay);
										if(day==todaysDay)
										  {	 
											cumulativeQty =Double.parseDouble(foreCastNode.getTextContent());
											
											cumulativeQty=(cumulativeQty*lastDayOfMonth)/day;
									        //cumulativeQty =(cumulativeQty*30)/30;									        
											for(int dayOfMonth=1; dayOfMonth<=lastDayOfMonth; dayOfMonth++)
									        {
									        	chartData.append("<set value='0'/>");
									        }
									       chartData.append("<set value='" + cumulativeQty + "'/>");
								          
										 }
									       
									       
								    }								
							  
						       }
					     }
					}
				}
				
				
				chartData.append("</dataset>");
				//5. End dataset for Forecasting
				
				//2. start dataset for Last year Quantity
			
				chartData.append("<dataset seriesName='Cumulative Last Year'  renderAs='Line'>");
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{
					unitNode = unitList.item(nodCtr);
					dateList = unitNode.getChildNodes();
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						dateNode   = dateList.item(dateCtr);
						dayQtyList = dateNode.getChildNodes();

						for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
						{
							//dayNode = dayQtyList.item(dateCtr);
							dayNode = dayQtyList.item(dayCtr);
							NodeList prevYearQtyList = dayNode.getChildNodes();

							for (int prevCtr = 0; prevCtr < prevYearQtyList.getLength(); prevCtr++)
							{
								Node prevYearQtyNode = prevYearQtyList.item(prevCtr);
								
								if(prevYearQtyNode.getNodeName().equals("pyr_dayqty"))
								{
								  prevYearQtyNode.getTextContent();
								 // out.println("PredayQty==="+prevYearQtyNode.getTextContent());
								  chartData.append("<set value='" + prevYearQtyNode.getTextContent() + "'/>");
							     }
							}
						}
					}
				}
				chartData.append("</dataset>");	
				//2. End dataset for Last year Quantity
				//3. Start dataset for Daily Budget Quantity
				
				chartData.append("<dataset seriesName='Cumulative Budget'  renderAs='Line'>");
				
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{
					unitNode = unitList.item(nodCtr);
					dateList = unitNode.getChildNodes();
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						dateNode   = dateList.item(dateCtr);
						dayQtyList = dateNode.getChildNodes();

						for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
						{
							dayNode = dayQtyList.item(dayCtr);
							NodeList dailyBdgtList = dayNode.getChildNodes();

							for (int dBdgtCtr = 0; dBdgtCtr < dailyBdgtList.getLength(); dBdgtCtr++)
							{
								Node dailyBdgtNode = dailyBdgtList.item(dBdgtCtr);
								
								if(dailyBdgtNode.getNodeName().equals("daily_budqty"))
								{
									dailyBdgtNode.getTextContent();
									//out.println("daliyBdgtQty==="+dailyBdgtNode.getTextContent());
								    chartData.append("<set value='" + dailyBdgtNode.getTextContent() + "'/>");
							     }
							}
						}
					}
				}
				chartData.append("</dataset>");					
			//3. End dataset for Daily Budget Quantity
			//4. Start dataset for Daily Budget Quantity
             chartData.append("<dataset seriesName='Cumulative Production' >");
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{
					unitNode = unitList.item(nodCtr);
					dateList = unitNode.getChildNodes();
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						dateNode   = dateList.item(dateCtr);
						dayQtyList = dateNode.getChildNodes();

						for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
						{
							dayNode = dayQtyList.item(dayCtr);
							NodeList curCumQtyList = dayNode.getChildNodes();
							
							for (int curCumCtr = 0; curCumCtr < curCumQtyList.getLength(); curCumCtr++)
							{
								Node curCumQtyNode = curCumQtyList.item(curCumCtr);
								
								if(curCumQtyNode.getNodeName().equals("cur_cumqty")  )
								{
									curCumQtyNode.getTextContent();
									//out.println("cumuQty==="+curCumQtyNode.getTextContent());
								  chartData.append("<set value='" + curCumQtyNode.getTextContent() + "'/>");
							     }
							}
						}
					}
				}
				chartData.append("</dataset>");					
		//4. End dataset for Daily Budget Quantity	
			//1. start dataset for Day wise Quantity

				chartData.append("<dataset seriesName='Day Production'>");
				for (int nodCtr = 0; nodCtr < unitList.getLength(); nodCtr++)
				{
					unitNode = unitList.item(nodCtr);
					dateList = unitNode.getChildNodes();		
					
					
					for (int dateCtr = 0; dateCtr < dateList.getLength(); dateCtr++)
					{
						dateNode = dateList.item(dateCtr);
						
						dayQtyList = dateNode.getChildNodes();
						
						for (int dayCtr = 0; dayCtr < dayQtyList.getLength(); dayCtr++)
						{
							
							dayNode = dayQtyList.item(dayCtr);							
							dayQty = dayNode.getAttributes().item(0).getNodeValue();
							chartData.append("<set value='" + dayQty + "'/>");
						}
					}
					
					
				}
				chartData.append("</dataset>");
				//1. End dataset for Day wise Quantity			
				chartData.append("</chart>");
				chartDataList.add(chartData.toString());
				System.out.println("chartData is  :" + chartData.toString() + "Chart data List sizeee is =" + chartDataList.size());
				chartData.setLength(0);
				
			}
		}
			else{
				%>
				<table  cellspacing="1" cellpadding="2" align="center">
				<tr><td><h4> No data found !</h4></td></tr>
				</table>				
				<%
				
			}
		}

		int chartDivId = 0;
		int countChart=0;
		int tablId=0;
		
		%>
		<table border="1" cellspacing="1" cellpadding="2">
		<%
		 
		for (String chartDatFrmList : chartDataList)
		{
			chartDivId++;
           %>          
            <% if(tablId ==0 || (tablId%3==0))
            {
		   %>
            	<tr>
            <%	
            	tablId=0;
            }
            %>
            
	       <td align ="left" style="font-size:12px"><b> <%=geoLocList.get(countChart)%> - <%=unitFormList.get(countChart)%> </b>
	       <div id="chartContainer<%=chartDivId%>">Chart will load here ! </div>
           
	         <script type="text/javascript"> 
		         FusionCharts.setCurrentRenderer('javascript');
		         var myChart = new FusionCharts("<%=srcImagesPath%>", "myChartId", "370", "350", "0", "0");
		         myChart.setXMLData("<%=chartDatFrmList%>");          
		         myChart.render("chartContainer<%=chartDivId%>");      
              </script>
            </td>
            
            
            <% if(tablId >0 && tablId%3==0)
            {
		   %>
            	</tr>
            <%	
            }
            %>
         <%
         tablId++;
         countChart++;
	     }
		%>
	</table>
		<%
	   } catch (Exception ex)
	{
		System.out.println("Exception : ProductionVsBudgetReport.jsp :" + ex.getMessage());
	}
%>

</body>
</html>
