package ibase.dashboard.mfg.ejb;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class MachineUtilizationDetails
 */
@Stateless
public  class MachineUtlDetails extends ValidatorEJB implements MachineUtlDetailsRemote, MachineUtlDetailsLocal {

	
    /**
     * Default constructor. 
     */
    public MachineUtlDetails() {
        // TODO Auto-generated constructor stub
    }
	
	public String getSiteCodeList() throws RemoteException,ITMException
	{
		
		StringBuffer xmlData = null;
    	String sql = "";
		ResultSet rs = null;		
		PreparedStatement pstmt = null;
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			sql="select distinct site_code,descr FROM site ORDER BY site_code";
			pstmt = conn.prepareStatement(sql); 
			rs = pstmt.executeQuery();
			xmlData = new StringBuffer("<?xml version=\"1.0\"?><Root>");
			while(rs.next())
			{
				xmlData.append("<Detail>");				
				xmlData.append("<site_code>").append("<![CDATA[" + checkNull(rs.getString("site_code"))+"]]>").append("</site_code>");
				xmlData.append("<descr>").append("<![CDATA[" + checkNull(rs.getString("descr"))+"]]>").append("</descr>");
				xmlData.append("</Detail>");
			}
			xmlData.append("</Root>");
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (rs != null)
						rs.close();
					rs = null;
					if (pstmt != null)
						pstmt.close();
					pstmt = null;
					conn.close();
					conn = null;
				}
				conn = null;
			} catch (Exception d)
			{
				d.printStackTrace();
				System.out.println("Exception in :MachineUtilizationDetails:getSiteCode:"+d.getMessage());
				throw new ITMException(d);
			}
		}
		return xmlData.toString();
	}
	
	
	public String getMachineUtlDetailsBySiteCode(String siteCode,String month,String year) throws RemoteException,ITMException
	{
		String sql = "";
		ResultSet rs = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		ResultSet rs3 = null;
		ResultSet rs4 = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmt2 = null;
		PreparedStatement pstmt3 = null;
		PreparedStatement pstmt4 = null;
		ConnDriver connDriver = null;
		StringBuffer xmlData =new StringBuffer();
		String pre_workDate="";
		int count=0;
		String currentWrkDate ="";
		SimpleDateFormat simpleDateFormat=null,sdf =null;
	    String curentDateString=null;
	    Date currentDate=null;
	    Date workDate=null;
	    String shift="";
	    Calendar calendar=null;
	    String wrkDateInString="";
	    int day=1;	    
	    String workOrder="";
	    int operation=0;
	    String fromDate="";
	    String toDate="";
		  int number=0;

		try
		{ 
			//here date & time activity 
			simpleDateFormat = new SimpleDateFormat("dd-MMM-yy");
			sdf= new SimpleDateFormat("yyyy-MM-dd");
			curentDateString= sdf.format(new java.util.Date());
			currentDate = sdf.parse(curentDateString);
			
			
			//ADD-------1St of month and last of month
			 calendar =Calendar.getInstance();
			 calendar.set(Integer.parseInt(year), Integer.parseInt(month), day);
		     fromDate = simpleDateFormat.format(calendar.getTime());
		     System.out.println(" 1st date of month="+fromDate);       
		     
		     calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		     toDate = simpleDateFormat.format(calendar.getTime());
		     System.out.println("last date of month="+toDate); 
		     
		   //End of -------1St of month and last of month
			System.out.println("from date in side Machine Utilization ="+fromDate);
			System.out.println("toDate date in Machine Utilization="+toDate);
			connDriver=new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;	
			
		     xmlData = new StringBuffer("<?xml version=\"1.0\"?><Root>");
		     sql="SELECT DISTINCT WORK_CTR, DESCR FROM WORKCNTR WHERE SITE_CODE =? ORDER BY WORK_CTR";
		     pstmt=conn.prepareStatement(sql);
		     pstmt.setString(1,siteCode);
		    rs = pstmt.executeQuery();
			while (rs.next())
			{   count=0;
				xmlData.append("<Detail>");
				
				String wrkCenter=checkNull(rs.getString("WORK_CTR"));
				xmlData.append("<work_ctr  wrkcenter=\""+wrkCenter+"\">");
				xmlData.append("<descr>").append("<![CDATA["+checkNull(rs.getString("DESCR"))+"]]>").append("</descr>");		
				
				sql="SELECT work_date,shift from work_calendar " + 
				" where (work_date between ? and ?) and site_code=?";
				pstmt1=conn.prepareStatement(sql);
				pstmt1.setString(1,fromDate);
				pstmt1.setString(2,toDate);
				pstmt1.setString(3,siteCode); 
				rs1=pstmt1.executeQuery();
			
				while (rs1.next())
				{   
					count++;
					currentWrkDate=checkNull(rs1.getString("work_date"));
					if(count>1 && !pre_workDate.equals(currentWrkDate))
					{						 
						 xmlData.append("</work_date>");
					}
					if(count==1 || !pre_workDate.equals(currentWrkDate))
					{
					  xmlData.append("<work_date date=\""+currentWrkDate+"\">");
					  pre_workDate=currentWrkDate;
					}
					  shift=rs1.getString("shift");
					  if(shift!=null && shift.trim().length()>0)
					  {
								  xmlData.append("<shift shift=\""+shift+"\">");	
							      workDate=sdf.parse(sdf.format(rs1.getTimestamp("work_date")));
								  calendar=Calendar.getInstance();
								  calendar.setTime(rs1.getDate("work_date"));
								  wrkDateInString=simpleDateFormat.format(calendar.getTime());
							  if(workDate.before(currentDate))
							  {
								    sql="SELECT WORK_ORDER,OPERATION,shift FROM WORKORDER_FEEDBACK WHERE(START_TIME BETWEEN  '"+wrkDateInString+"'  AND '"+ wrkDateInString+"') AND SITE_CODE = ? AND WORK_CTR = ? AND SHIFT = ?";
								    pstmt2=conn.prepareStatement(sql);
								    pstmt2.setString(1,siteCode);
									pstmt2.setString(2,wrkCenter);
									pstmt2.setString(3,shift);
									rs2=pstmt2.executeQuery();
									if(rs2.next())
									  {
										workOrder  =checkNull(rs2.getString("WORK_ORDER"));
										operation  =rs2.getInt("OPERATION");
									      sql="select w.item_code, i.descr,  w.work_order, w.work_ctr,w.start_date, w.end_date  from  worder_route w ,item i where  w.item_code=i.item_code and w.work_order = ? and w.operation=? and w.work_ctr=? ";
										  pstmt4=conn.prepareStatement(sql);
										  pstmt4.setString(1, workOrder);
										  pstmt4.setInt(2, operation);
										  pstmt4.setString(3, wrkCenter);
										  rs4= pstmt4.executeQuery();
										   number=0;
										  while(rs4.next())
							                    {
											       number++;
												  xmlData.append("<actual_used color=\""+"lightgreen"+"\">");
												  xmlData.append("<work_order>").append("<![CDATA["+checkNull(rs4.getString("work_order"))+"]]>").append("</work_order>");
												  xmlData.append("<item_code>").append("<![CDATA["+checkNull(rs4.getString("item_code"))+"]]>").append("</item_code>");
												  xmlData.append("<item_descr>").append("<![CDATA["+checkNull(rs4.getString("descr"))+"]]>").append("</item_descr>");
												  xmlData.append("<work_ctr>").append("<![CDATA["+checkNull(rs4.getString("work_ctr"))+"]]>").append("</work_ctr>");
												  xmlData.append("<start_date>").append("<![CDATA["+checkNull(rs4.getString("start_date"))+"]]>").append("</start_date>");
												  xmlData.append("<end_date>").append("<![CDATA["+checkNull(rs4.getString("end_date"))+"]]>").append("</end_date>");
												  
												  xmlData.append("</actual_used>");
							                    }
										  
										  if(number==0)
										  {
											  xmlData.append("<actual_used color=\""+"lightgray"+"\">  </actual_used>");
										  }
											  rs4.close();
											  rs4=null;
											  pstmt4.close();
											  pstmt4=null;
									  
									  }else
							          {
										  xmlData.append("<actual_used color=\""+"lightgray"+"\">  </actual_used>");
							          }
									
									pstmt2.close();
									pstmt2=null;
									rs2.close();
									rs2=null;
							  }
							  else
							  {
								 sql=" SELECT WORK_ORDER,OPERATION,SHIFT FROM MACHINE_LOAD_DET WHERE(LOAD_DATE BETWEEN '"+wrkDateInString+"' AND '"+wrkDateInString+"') AND SITE_CODE=? AND WORK_CTR= ? AND SHIFT=?";
								    pstmt3=conn.prepareStatement(sql);
								    pstmt3.setString(1,siteCode);
									pstmt3.setString(2,wrkCenter);
									pstmt3.setString(3,shift);
									rs3=pstmt3.executeQuery();
									if(rs3.next())
								    {
										workOrder  =checkNull(rs3.getString("WORK_ORDER"));
										operation  =rs3.getInt("OPERATION");
									  sql="select w.item_code, i.descr,  w.work_order, w.work_ctr,w.start_date, w.end_date  from  worder_route w ,item i where  w.item_code=i.item_code and w.work_order = ? and w.operation=? and w.work_ctr=?";
									  pstmt4=conn.prepareStatement(sql);
									  pstmt4.setString(1, workOrder);
									  pstmt4.setInt(2, operation);
									  pstmt4.setString(3, wrkCenter);
									  rs4= pstmt4.executeQuery();
									  number=0;
									  while (rs4.next())
						                    {
										      number++;
											  xmlData.append("<actual_used color=\""+"yellow"+"\">");
											  xmlData.append("<work_order>").append("<![CDATA["+checkNull(rs4.getString("work_order"))+"]]>").append("</work_order>");
											  xmlData.append("<item_code>").append("<![CDATA["+checkNull(rs4.getString("item_code"))+"]]>").append("</item_code>");
											  xmlData.append("<item_descr>").append("<![CDATA["+checkNull(rs4.getString("descr"))+"]]>").append("</item_descr>");
											  xmlData.append("<work_ctr>").append("<![CDATA["+checkNull(rs4.getString("work_ctr"))+"]]>").append("</work_ctr>");
											  xmlData.append("<start_date>").append("<![CDATA["+checkNull(rs4.getString("start_date"))+"]]>").append("</start_date>");
											  xmlData.append("<end_date>").append("<![CDATA["+checkNull(rs4.getString("end_date"))+"]]>").append("</end_date>");
											  xmlData.append("</actual_used>");
						                    }
									  
									  if(number==0)
									  {
										  xmlData.append("<actual_used color=\""+"white"+"\"> </actual_used>");  
									  }
										  rs4.close();
										  rs4=null;
										  pstmt4.close();
										  pstmt4=null;
								 }
								 else
								 {
									  xmlData.append("<actual_used color=\""+"white"+"\"> </actual_used>");
								 }
								    pstmt3.close();
									pstmt3=null;
									rs3.close();
									rs3=null;
							  }
							  xmlData.append("</shift>");
						}
				}
				if(count>0)
				{
					 xmlData.append("</work_date>");
				}
				rs1.close();
				rs1=null;
				pstmt1.close();
				pstmt1=null;
				xmlData.append("</work_ctr>");
				xmlData.append("</Detail>");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			xmlData.append("</Root>");
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (rs != null)
						rs.close();
					rs = null;
					if (pstmt != null)
						pstmt.close();
					pstmt = null;
					conn.close();
					conn = null;
				}
				conn = null;
			} catch (Exception d)
			{
				d.printStackTrace();
				System.out.println("Exception in :: MachineUtilizationDetails:getMachineUtyListBySiteCode:"+d.getMessage());
				throw new ITMException(d);
			}
		}
		return xmlData.toString();
	}	
	private String checkNull(String input)
	{
		if (input == null)
		{
			input = "";
		} else
		{
			input = input.trim();
		}
		return input;
	}
}

