package ibase.webitm.ejb.adv;

import ibase.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;

import java.util.Date;
import java.util.Calendar;
import java.text.*;
import java.sql.*;
import java.rmi.RemoteException;
import java.util.zip.DataFormatException;

import javax.naming.InitialContext;
import javax.ejb.Stateless;

@Stateless

public class WIPScanConfPvSolar extends ActionHandlerEJB implements WIPScanConfPvSolarRemote,WIPScanConfPvSolarLocal
{
	public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("!!! $$ Confirm method $$ !!! ");
		GenericUtility genericUtility = null;
		ITMDBAccessEJB itmDBAccessEJB =null;
		Connection conn = null;
		ConnDriver connDriver = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String itemCode="";
		StringBuffer xmlBuffer = new StringBuffer();
		GenericUtility genutility=null;
		SimpleDateFormat sdf=null;
		SimpleDateFormat sdf2=null;		
		//varialble declaration for workorder receipt xml gena
		String workOrder = "";
		String siteCode = "";
		String loCoInsp = "";
		String xmlString = "";
		int rowcnt = 0;
		String qcReqd = "";
		int shelfLife = 0;
		String loCoAprv ="";
		Date expDate = null;
		String sql = null;
		Date relDate  = null;
		String tranIdForReciept="";
		boolean status = false;
		String retString = "";
		//varible declaration end for xml
		xmlBuffer.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
		xmlBuffer.append("<DocumentRoot>");
		System.out.println("Xml creation");
		xmlBuffer.append("<description>").append("Datawindow Root").append("</description>");
		xmlBuffer.append("<group0>");
		xmlBuffer.append("<description>").append("Group0 description").append("</description>");
		xmlBuffer.append("<Header0>");
		xmlBuffer.append("<objName><![CDATA[").append("worder_rcp").append("]]></objName>");
		xmlBuffer.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
		xmlBuffer.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
		xmlBuffer.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
		xmlBuffer.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
		xmlBuffer.append("<action><![CDATA[").append("SAVE").append("]]></action>");
		xmlBuffer.append("<elementName><![CDATA[").append("").append("]]></elementName>");
		xmlBuffer.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
		xmlBuffer.append("<taxKeyValue><![CDATA[").append("	").append("]]></taxKeyValue>");
		xmlBuffer.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
		xmlBuffer.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
		xmlBuffer.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
		xmlBuffer.append("<description>").append("Header0 members").append("</description>");

		try
		{
			genutility=GenericUtility.getInstance();
			genericUtility=GenericUtility.getInstance();
			sdf=new SimpleDateFormat(genutility.getApplDateTimeFormat());
			sdf2=new SimpleDateFormat(genutility.getApplDateFormat());
			itmDBAccessEJB = new ITMDBAccessEJB();
			connDriver = new ConnDriver();
			siteCode = genutility.getValueFromXTRA_PARAMS(xtraParams,"site_code");
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			conn.setAutoCommit(false);
			System.out.println("Tran Id"+tranID);
			System.out.println("^^^^^^^ Message: Forced Flag ..> " + forcedFlag);
			
			pstmt=conn.prepareStatement("SELECT WORK_ORDER,PRODUCT_CODE FROM WIP_SCANNING_HDR WHERE TRAN_ID = ?");
			pstmt.setString(1,tranID);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				workOrder = rs.getString(1);
				itemCode = rs.getString(2);
				
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;
			
			pstmt=conn.prepareStatement("SELECT SHELF_LIFE FROM ITEM WHERE ITEM_CODE = ?");
			pstmt.setString(1,itemCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				shelfLife = rs.getInt(1);
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;
			
			
			pstmt=conn.prepareStatement("SELECT  REL_DATE FROM WORKORDER WHERE WORK_ORDER = ?"); 
			pstmt.setString(1,workOrder);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				relDate = rs.getDate(1);
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;
			
			
			pstmt=conn.prepareStatement("SELECT LOC_CODE__INSP,QC_REQD,LOC_CODE_APRV FROM SITEITEM WHERE ITEM_CODE = ? AND LOC_CODE__INSP IS NOT NULL");
			pstmt.setString(1,itemCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				 loCoInsp = rs.getString(1);
				 qcReqd = rs.getString(2);
				 loCoAprv = rs.getString(2);
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;

			pstmt=conn.prepareStatement ("select wo.unit,wo.work_order,wo.item_code,wo.lot_no,wo.lot_sl,wf.tran_date,wf.start_time,wf.end_time,wf.site_code from workorder wo,workorder_feedback wf where wo.work_order = wf.work_order and wo.work_order = ? ORDER BY wf.start_time ");
			pstmt.setString(1,workOrder);				 
			rs=pstmt.executeQuery();
			System.out.println("^^^^^^tranId alias TRAN ID value^^^^^^:"+ tranID);
			System.out.println("Sql for xml genaration ");
			if(rs.next())
			{
				System.out.println("^^^^^^ BEFORE STARTING XML BUFFER^^^^^");
				System.out.println("^^^^^^tranId alias TRAN ID value^^^^^^:"+ tranID);
				xmlBuffer.append("<Detail1 objContext =\"1\"").append(" objName=\"worder_rcp\" domID=\"1\" dbID=\"\">");
				xmlBuffer.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
				xmlBuffer.append("<tran_id/>");
				xmlBuffer.append("<tran_date>").append("<![CDATA["+sdf2.format(new Date())+"]]>").append("</tran_date>\r\n");
				siteCode = rs.getString("site_code");
				xmlBuffer.append("<site_code>").append("<![CDATA[").append(rs.getString("site_code")).append("]]>").append("</site_code>\r\n");
				xmlBuffer.append("<work_order>").append("<![CDATA[").append(rs.getString("work_order")).append("]]>").append("</work_order>\r\n");
				xmlBuffer.append("<date__start>").append("<![CDATA["+sdf.format(rs.getDate("start_time"))+"]]>").append("</date__start>");
				xmlBuffer.append("<date__compl>").append("<![CDATA["+sdf2.format(new Date())+"]]>").append("</date__compl>\r\n");
				Calendar c=Calendar.getInstance(); 
				c.setTime(relDate);
				c.add(Calendar.MONTH,shelfLife);
				expDate=c.getTime();
				xmlBuffer.append("<exp_date>").append("<![CDATA[").append(sdf2.format(expDate)).append("]]>").append("</exp_date>\r\n");
				xmlBuffer.append("<item_code>").append("<![CDATA[").append(rs.getString("item_code")).append("]]>").append("</item_code>\r\n");
				xmlBuffer.append("<lot_no>").append("<![CDATA[").append(rs.getString("lot_no")).append("]]>").append("</lot_no>\r\n");
				xmlBuffer.append("<lot_sl>").append("<![CDATA[").append(rs.getString("lot_sl")).append("]]>").append("</lot_sl>\r\n");
				xmlBuffer.append("<quantity>").append("<![CDATA[1]]>").append("</quantity>\r\n");
				xmlBuffer.append("<std_qty>").append("<![CDATA[1]]>").append("</std_qty>\r\n");
				System.out.println("_____________-qc rejcted ______");
				if(qcReqd == "N")
				{
					xmlBuffer.append("<loc_code>").append("<![CDATA[").append(loCoAprv).append("]]>").append("</loc_code>\r\n");
				}
				else 
				{
					xmlBuffer.append("<loc_code>").append("<![CDATA[").append(loCoInsp).append("]]>").append("</loc_code>\r\n");
					xmlBuffer.append("<loc_code__aprv>").append("<![CDATA[").append(loCoAprv).append("]]>").append("</loc_code__aprv>\r\n");
				}
				
				xmlBuffer.append("<unit>").append("<![CDATA[").append(rs.getString("unit")).append("]]>").append("</unit>\r\n");
				xmlBuffer.append("<tran_type>").append("<![CDATA[").append("F").append("]]>").append("</tran_type>\r\n");
				xmlBuffer.append("<qc_reqd>").append("<![CDATA[").append("Y").append("]]>").append("</qc_reqd>\r\n");
				xmlBuffer.append("<no_art>").append("<![CDATA[").append(1).append("]]>").append("</no_art>\r\n");
				xmlBuffer.append("<chg_date/>");
				xmlBuffer.append("<chg_user/>");
				xmlBuffer.append("<chg_term/>");
				xmlBuffer.append("</Detail1>");
				xmlBuffer.append("</Header0>");
				xmlBuffer.append("</group0>");
				xmlBuffer.append("</DocumentRoot>");
				System.out.println("End of Xml string for xml");
				xmlString=xmlBuffer.toString();
				tranIdForReciept=saveData(siteCode, xmlString, conn);
				retString=tranIdForReciept;
				if (tranIdForReciept.indexOf("Success") > -1)
				{
					String[] arrayForTranId = tranIdForReciept.split("<TranID>");
					System.out.println("++++++++++++++=update hdr+++++++");
					sql="update wip_scanning_hdr set emp_code__aprv = ?, confirmed = ?, conf_date = ? where tran_id = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode"));
					pstmt.setString(2,"Y");
					pstmt.setTimestamp(3,new Timestamp(System.currentTimeMillis()));
					pstmt.setString(4,tranID);
					rowcnt = pstmt.executeUpdate();
					pstmt.close();
					pstmt = null;
					int endIndex = arrayForTranId[1].indexOf("</TranID>");
					tranIdForReciept = arrayForTranId[1].substring(0,endIndex);
					System.out.println("VOUCHER GENERATED SUCCESSFULLY");
					if(rowcnt > 0) 
					{
						conn.commit();	
						retString = itmDBAccessEJB.getErrorString("","VTSUCC1","","",conn);
						System.out.println("Voucher Confirmed Sucessfully.......");
					}
					conn.close();
					conn = null;
					
				}
				else
				{
					status =true;
					return retString;
				}
			}		
		}
		catch(SQLException se)
		{
			se.printStackTrace();
		}
		catch(DataFormatException de)
		{
			de.printStackTrace();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
				}
				pstmt = null;
				if (conn != null)
				{
					conn.close();
				}
				conn = null;
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

			System.out.println("Header xmlBuffer Generated"+xmlBuffer.toString());
			System.out.println("After xml Buffer end");
			rs=null;
			pstmt=null;
		}
		System.out.println("after finally block");
		System.out.println("^^^^^^^^^^^final return string _____-"+retString);
		return retString;
	}
	private String saveData(String siteCode, String xmlString, Connection conn) throws ITMException
	{
		System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			System.out.println("___________________in save method ");
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");

			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString :::: " + xmlString);
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString, true, conn);
			masterStateful = null;
			System.out.println("End of save method");
		}
		catch(ITMException itme)
		{
			itme.printStackTrace();
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return retString;
	}
	}

