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.webitm.ejb.ValidatorEJB;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;

import java.util.ArrayList;
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
	{  
		ValidatorEJB validatorEJB = new ValidatorEJB(); 
		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;		
		String workOrder = "",siteCode = "",loCoInsp = "",xmlString = "",currOperation = "",maxOperation="",confrm = "",userId = "",qcReqd = "",loCoAprv ="",workOrd = "";
		//int currOperation =0,maxOperation=0;
		ArrayList <String> errList=new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");
		ITMDBAccessEJB itmdbAccessEJB = new ITMDBAccessEJB();
		String errString="";
		boolean flag = false;
		String errCode="";
		String errFieldName="";
		String errorType="";
		int rowcnt = 0;
		int shelfLife = 0;
		Date expDate = null;
		String sql = "";
		Date  relDate  = null;
		String tranIdForReciept="";
		boolean status = false;
		String retString = "";

		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");
			System.out.println("SITE CODE  --->>> "+siteCode);
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			conn.setAutoCommit(false);
			System.out.println("Tran Id"+tranID);
			userId=validatorEJB.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("^^^^^^^ Message: Forced Flag ..> " + forcedFlag);
			//VALIDATION FOR CONFIRM TRANSECTION
			sql = " SELECT CONFIRMED FROM WIP_SCANNING_PS_HDR WHERE TRAN_ID = ?"; 
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1,tranID);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confrm = rs.getString(1);
				System.out.println("<<<<<,,,------confirmed column value------>>>>."+confrm );
				if("y".equalsIgnoreCase(confrm))
				{
					errString = itmdbAccessEJB.getErrorString("","VTWIPCONFT", "");
					System.out.println("vnfirmed transaction"+errString);
					return errString;
				}
				else 
				{
					flag=true;
				}
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;
			if(flag)
			{
				//GET OPERATION FROM WIP_SCANNING_PS_HDR TABLE
				sql = "SELECT MAX(OPERATION) FROM WIP_SCANNING_PS_HDR WHERE TRAN_ID = ?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1,tranID);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					currOperation = rs.getString(1);
					System.out.println("CURRENT OPERATION IN WIP SCANNING PS HDR TABLE["+currOperation+"]");
				}
				rs.close();
				pstmt.close();
				rs = null;
				pstmt = null;
				//GET WORK_ORDER,PRODUCT_CODE FROM WIP_SCANNING_PS_HDR TABLE
				sql = "SELECT WORK_ORDER,PRODUCT_CODE FROM WIP_SCANNING_PS_HDR WHERE TRAN_ID = ?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1,tranID);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					workOrd=rs.getString(1);
					itemCode = rs.getString(2);
					System.out.println("current operation in wip scanning ps hdr table"+itemCode);
					System.out.println("WORK ORDER "+workOrd);
				}
				rs.close();
				pstmt.close();
				rs = null;
				pstmt = null;
				
				//GET MAX(OPERATION) FROM  WORDER_ROUTE
				sql = " SELECT MAX(OPERATION) FROM WORDER_ROUTE WR ,WORKORDER W1 WHERE WR.WORK_ORDER= W1.WORK_ORDER AND W1.WORK_ORDER = ?" ;
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,workOrd);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					maxOperation = rs.getString(1);
					System.out.println("MAX OPERATION -----------["+maxOperation+"]");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;


				//GET SHELF_LIFE FROM ITEM
				sql = "SELECT SHELF_LIFE FROM ITEM WHERE ITEM_CODE = ?";
				pstmt=conn.prepareStatement(sql);
				pstmt.setString(1,itemCode);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					shelfLife = rs.getInt(1);
				}
				rs.close();
				pstmt.close();
				rs = null;
				pstmt = null;
				//GET REL DATE FROM WORKORDER  
				sql = "SELECT  REL_DATE FROM WORKORDER WHERE WORK_ORDER = ?";
				pstmt=conn.prepareStatement(sql); 
				pstmt.setString(1,workOrd);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					relDate = rs.getDate(1);
					//relDate =sdf.format(new Date()) ;
					
				}
				rs.close();
				pstmt.close();
				rs = null;
				pstmt = null;
				//CALCULATIN FOR EXPIRY DATE
				Calendar c=Calendar.getInstance(); 
				Date d1 = new Date();
				relDate = d1;
				c.setTime(relDate);
				c.add(Calendar.MONTH,shelfLife);
				expDate=c.getTime();
				System.out.println("EXPERY DATE OF METARIAL>>>>>."+expDate);
				//GET LOC_CODE__INSP,QC_REQD,LOC_CODE_APRV FROM SITEITEM
				sql = "SELECT LOC_CODE__INSP,QC_REQD,LOC_CODE_APRV FROM SITEITEM WHERE ITEM_CODE = ? AND LOC_CODE__INSP IS NOT NULL";
				pstmt=conn.prepareStatement(sql);
				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;
				//GET UNIT,WORK_ORDER,ITEM_CODE,LOT_NO,LOT_SL,TRAN_DATE,START_TIME,END_TIME,SITE_CODE FROM WORKORDER ,WORKORDER_FEEDBACK
				sql = "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=conn.prepareStatement(sql);
				pstmt.setString(1,workOrd);				 
				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("IN RESULT SET  FOR  RECEIPT CALL");
					if(maxOperation.equalsIgnoreCase(currOperation))
					{	
						System.out.println("<<<<<<<<<---XML FOR WORKORDER RECEIPT------>>>>>>>>>>...");
						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>");
						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");

						xmlBuffer.append("<exp_date>").append("<![CDATA["+sdf2.format(new Date())+"]]>").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();
						System.out.println("______________-XML STRING VALUE_____________"+xmlString);
						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_PS_HDR SET EMP_CODE__APRV = ?, CONFIRMED = ?, CONF_DATE = ? WHERE WORK_ORDER = ? ";
							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,workOrd);
							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);
							}

						}
					}
					else
					{
						
						
							retString = itmDBAccessEJB.getErrorString("","VTWIPCOPR","","",conn);
							System.out.println("receipt can not be genrate");
							
												
					}

				}
			}
		}
		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;
		}

		int errListSize=errList.size();
		if(errListSize>0)
		{
			for(int cnt=0;cnt<errListSize;cnt++)
			{
				errCode=errList.get(cnt);
				errFieldName=errFields.get(cnt);
				errString=getErrorString(errFieldName, errCode, userId);
				errorType =  errorType( conn , errCode );

				if ( errString.length() > 0)
				{
					String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
					bifurErrString = bifurErrString;
					bifurErrString = bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>"));
					errStringXml.append(bifurErrString);
					errString = "";
				}

				if ( errorType.equalsIgnoreCase("E"))
				{
					break;
				}
			}
			errList.clear();
			errList = null;
			errFields.clear();
			errFields = null;
			errStringXml.append("</Errors></Root>\r\n");
		}else
		{
			errStringXml = new StringBuffer( "" );

		}
		System.out.println("after finally block");
		System.out.println("^^^^^^^^^^^FINAL RETURN STRING FROM CONFIRM-.["+retString+"]");
		return retString;

	}
	private String errorType( Connection conn , String errorCode )
	{
		String msgType = "";
		System.out.println("IN ERROR METHOD");
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		try
		{
			String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO =   ? ";
			System.out.println("SQL IS EXECUTING");
			pstmt = conn.prepareStatement( sql );
			pstmt.setString( 1, errorCode );
			rs = pstmt.executeQuery();
			while( rs.next() )
			{
				msgType = rs.getString("MSG_TYPE");
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}
		}
		return msgType;
	}

	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();
		}
		System.out.println("<<<<<<<<<, RETURN STRING FROM SAVE DATA  >>>>.["+retString+"]");
		return retString;
	}
}

