/********************************************************
	Title 	 : 	QCSampleWizPos[M14HFRA001]
	Date  	 : 	02/12/14
	Developer:  Sagar M.

********************************************************/
package ibase.webitm.ejb.mfg;

import ibase.system.config.*;

import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.dis.InvAllocTraceBean;
import ibase.webitm.ejb.dis.StockUpdate;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.dis.adv.StockTransferConf;
import ibase.webitm.ejb.mfg.adv.ConfirmQcSample;

import java.io.*;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import org.w3c.dom.*;

import javax.ejb.*;
import javax.naming.InitialContext;
@javax.ejb.Stateless
public class QCSampleWizPos extends ValidatorEJB implements QCSampleWizPosLocal, QCSampleWizPosRemote
{
	public String postSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String postSave(String domString, String tranId,String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		
		PreparedStatement pstmt = null;
        ResultSet rs = null;
        StockTransferConf stockTranConf = new StockTransferConf();
        ConfirmQcSample qcSampleConf= new ConfirmQcSample();
        GenericUtility genericUtility = GenericUtility.getInstance();
        DistCommon dist =  new DistCommon();
        String empCodeSample="";
        String xmlString = null;
        String siteCode="",qorderNo="",itemCode="",lotNo="",lotSl="",remarks="",unit="";
        String qcOrdNo="",locCodeTo="",lotNoTo="",lotSlTo="",procMth="",chgTerm="",userId="",tranIdQcSamp="";
        String forcedFlag = "false";
		String errString = "";
		String sql = "";
        int lineNo=0,lineNoSl=0,stepNo=1,newLine=0;
        int parentNodeListLength = 0;
        double sampleQty=0.0,convFactor=0.0,stdQty=0.0;
        Document dom = null;
        NodeList hdrDom=null;
        NodeList parentNodeList = null;
		Node parentNode = null;
        StringBuffer xmlBuff = null;
        Date currentDate = new Date();
        boolean isError = false;
        boolean toCommit = false;
        
		try
		{
			System.out.println(">>>>>>>In post Save conn:"+conn);
			conn.setAutoCommit(false);
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			chgTerm = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" ));
			System.out.println( ">>>>>>>>>QCSampleWizPos tranId:"+tranId);
			System.out.println(">>>>>>>>>>>>>>>>>>>>>domString in post save:"+domString);
			dom = genericUtility.parseString(domString);
			System.out.println(">>>>>>>>>>Calling stockTranConf Confirm method:"+tranId);
			errString = stockTranConf.confirm( tranId, xtraParams, forcedFlag, conn, toCommit);
			System.out.println(">>>>>>>>stockTranConf.confirm return errString:"+errString);
			if(errString == null || errString.trim().length() == 0)
			{
				hdrDom = dom.getElementsByTagName("Detail2");
				if(hdrDom != null && hdrDom.getLength() > 0)
				{
					qcOrdNo = genericUtility.getColumnValueFromNode("qc_ord__no", dom.getElementsByTagName("Detail1").item(0));
					siteCode = genericUtility.getColumnValueFromNode("site_code", dom.getElementsByTagName("Detail2").item(0));
				    System.out.println(">>>>>>>>>>qcOrdNo:"+qcOrdNo); 
				    System.out.println(">>>>>>>>>>siteCode:"+siteCode);
				}
				//Get data from qc Order..
				sql = "select item_code,lot_no,lot_sl,unit from qc_order where qorder_no = ? ";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1, qcOrdNo);
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
				   itemCode = rs.getString(1) == null ? "" : rs.getString(1);
				   lotNo = rs.getString(2) == null ? "" : rs.getString(2);
				   lotSl = rs.getString(3) == null ? "" : rs.getString(3);
				   unit = rs.getString(4) == null ? "" : rs.getString(4);
				}
				pstmt.close();
				rs.close();
				pstmt = null;
				rs = null;
				//if unit is null then get unit from item..
				if(unit == null || unit.trim().length() == 0 )
				{
					sql = "select unit from item where item_code = ? ";
					pstmt= conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					rs = pstmt.executeQuery(); 
					if(rs.next())
					{
					   unit = rs.getString(1) == null ? "" : rs.getString(1);
					}
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;
				}
				
				System.out.println(">>>>>>Generate XML For saveDate() of QC Sample Header>>>>>>");
				remarks="Auto Generate From QC Sampling Wiz"; 
				//Start prepare xml..
				xmlBuff = null;	
				xmlBuff = new StringBuffer();
				xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
				xmlBuff.append("<DocumentRoot>");
				xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
				xmlBuff.append("<group0>");
				xmlBuff.append("<description>").append("Group0 description").append("</description>");
				xmlBuff.append("<Header0>");
				xmlBuff.append("<objName><![CDATA[").append("qc_sample").append("]]></objName>");         
				xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
				xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
				xmlBuff.append("<description>").append("Header0 members").append("</description>");
				xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"qc_sample\" objContext=\"1\">");  
				xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
				xmlBuff.append("<tran_id/>");
				xmlBuff.append("<tran_date><![CDATA["+ sdf.format(currentDate).toString() +"]]></tran_date>");
				xmlBuff.append("<site_code><![CDATA["+ siteCode.trim()  +"]]></site_code>");
				xmlBuff.append("<qorder_no><![CDATA["+ qcOrdNo.trim()  +"]]></qorder_no>");
				xmlBuff.append("<tran_type/>");
				xmlBuff.append("<item_code><![CDATA["+ itemCode.trim()  +"]]></item_code>");
				xmlBuff.append("<loc_code><![CDATA["+ locCodeTo.trim()  +"]]></loc_code>");
				xmlBuff.append("<lot_no><![CDATA["+ lotNo.trim()  +"]]></lot_no>");
				xmlBuff.append("<lot_sl><![CDATA["+ lotSl.trim()  +"]]></lot_sl>");
				xmlBuff.append("<remarks><![CDATA["+ remarks  +"]]></remarks>");
				xmlBuff.append("<emp_code__sample><![CDATA["+ empCodeSample  +"]]></emp_code__sample>");
				xmlBuff.append("<confirmed><![CDATA["+ "N"  +"]]></confirmed>");
				xmlBuff.append("<conf_date/>");
				xmlBuff.append("<emp_code__aprv/>");
				xmlBuff.append("<chg_date><![CDATA["+ sdf.format(currentDate).toString() +"]]></chg_date>");
				xmlBuff.append("<chg_user><![CDATA["+ userId +"]]></chg_user>");
				xmlBuff.append("<chg_term><![CDATA["+ chgTerm +"]]></chg_term>");
				xmlBuff.append("</Detail1>");
				
			    sql = "select proc_mth from siteitem where site_code = ? and item_code = ? ";
				pstmt= conn.prepareStatement(sql);
				pstmt.setString(1, siteCode);
				pstmt.setString(2, itemCode);
				rs = pstmt.executeQuery(); 
				if(rs.next())
				{
				   procMth = rs.getString(1) == null ? "" : rs.getString(1);
				}
				pstmt.close();
				rs.close();
				pstmt = null;
				rs = null;
				if(procMth == null || procMth.trim().length() == 0)
				{
					sql = " select proc_mth from item where item_code = ? ";
					pstmt= conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					rs = pstmt.executeQuery(); 
					if(rs.next())
				    {
					    procMth = rs.getString(1) == null ? "" : rs.getString(1);
				    }
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;
				}
				//Get Detail4 data from dom......
				parentNodeList = dom.getElementsByTagName("Detail4");
				parentNodeListLength = parentNodeList.getLength();
				System.out.println(">>>>>>>>in parentNodeListLength:"+parentNodeListLength);
				for(int ctr = 0; ctr < parentNodeListLength ; ctr++ )
				{
					newLine++; 
					System.out.println(">>>>>>>>>>>>>Get dom (Detail4 details:"+newLine);
					parentNode = parentNodeList.item(ctr);
					lineNo = Integer.parseInt(genericUtility.getColumnValueFromNode("line_no", parentNode).trim());
					locCodeTo = genericUtility.getColumnValueFromNode("loc_code__to", parentNode);
					lotNoTo = genericUtility.getColumnValueFromNode("lot_no__to", parentNode);
					lotSlTo = genericUtility.getColumnValueFromNode("lot_sl__to", parentNode);
					sampleQty = Double.parseDouble(genericUtility.getColumnValueFromNode("sample_qty", parentNode));
					lineNoSl = Integer.parseInt(genericUtility.getColumnValueFromNode("line_no_sl", parentNode));
					System.out.println(">>>>>>>>>lineNoSl"+lineNoSl);
					System.out.println(">>>>>>dom sampleQty:"+sampleQty);
					
                    
					if(sampleQty > 0)
					{
						System.out.println(">>>>>>>>>>>>Adding record for QC Sample Details");
						//Get Std. Quantity and Conv. Factor...
					    ArrayList unitList = null;
						Object factOb = null,qtyOb = null;
						unitList = dist.getConvQuantityFact( unit,unit, itemCode, sampleQty, 0,conn);
						factOb = unitList.get(0);
						qtyOb = unitList.get(1);
						convFactor=Double.parseDouble(factOb.toString());
						stdQty=Double.parseDouble(qtyOb.toString());
					    System.out.println(">>>>>>>>convFactor:"+convFactor); 
					    System.out.println(">>>>>>>>stdQty:"+stdQty);
					    xmlBuff.append("<Detail2 dbID='' domID=\"1\" objName=\"qc_sample\" objContext=\"2\">");  
						xmlBuff.append("<attribute pkNames=\"\" selected=\"N\" updateFlag=\"A\" status=\"N\" />");
						xmlBuff.append("<tran_id/>");
						xmlBuff.append("<line_no>" + newLine + "</line_no>"); 
						xmlBuff.append("<iss_type><![CDATA["+ "A" +"]]></iss_type>");
						xmlBuff.append("<loc_code><![CDATA["+ locCodeTo.trim() +"]]></loc_code>");
						xmlBuff.append("<lot_no><![CDATA["+ lotNoTo.trim() +"]]></lot_no>");
						xmlBuff.append("<lot_sl><![CDATA["+ lotSlTo.trim() +"]]></lot_sl>");
						xmlBuff.append("<stock_det/>");
						xmlBuff.append("<qty_sample><![CDATA["+ sampleQty +"]]></qty_sample>");         
						xmlBuff.append("<unit><![CDATA["+ unit.trim() +"]]></unit>");
						xmlBuff.append("<unit__std><![CDATA["+ unit.trim() +"]]></unit__std>");
						xmlBuff.append("<conv_qty__stduom><![CDATA["+ convFactor +"]]></conv_qty__stduom>");  
						xmlBuff.append("<qty_sample_stduom><![CDATA["+ stdQty +"]]></qty_sample_stduom>");   
						xmlBuff.append("<remarks><![CDATA["+ remarks +"]]></remarks>");
						xmlBuff.append("<step_no><![CDATA["+ stepNo +"]]></step_no>");     
						xmlBuff.append("<proc_mth><![CDATA["+ procMth.trim() +"]]></proc_mth>");
						xmlBuff.append("<line_no_sl><![CDATA["+ lineNoSl +"]]></line_no_sl>");   
						xmlBuff.append("<bal_qty/>");
						xmlBuff.append("</Detail2>");
					}
				}
				xmlBuff.append("</Header0>");
				xmlBuff.append("</group0>");
				xmlBuff.append("</DocumentRoot>");
				xmlString = xmlBuff.toString();
				//End prepare xml..
				siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
				errString = saveData(siteCode,xmlString,conn);
				System.out.println(">>>>>>errString after saveData:"+errString);
				if (errString.indexOf("Success") > -1)
				{
					String[] arrayForTranId = errString.split("<TranID>");
					System.out.println("@@@@ arrayForTranId:["+arrayForTranId.toString()+"]arrayForTranId.length["+arrayForTranId.length+"]");
					int endIndex = arrayForTranId[1].indexOf("</TranID>");
					tranIdQcSamp = arrayForTranId[1].substring(0,endIndex);
					System.out.println(">>>>>>>>>>>>>>>QC Sampling Tran Id:"+tranIdQcSamp);
					errString="";
					//Call QC Sample Confirmation......
					errString =qcSampleConf.actionConfirm(tranIdQcSamp, xtraParams, conn);
					System.out.println(">>>>>>>>After Calling QC Sample Confirmation errString:"+errString);
					if(errString.indexOf("CONQCSUCC") > -1)
					{
						System.out.println(">>>>>>>>>>QC Sample Transaction Confirmed Successfully:"+tranIdQcSamp);
						isError=false;
					}
					else
					{
						System.out.println(">>>>>>>>>>QC Sample Transaction Not Confirmed:"+tranIdQcSamp);
						isError=true;	
					}
				}
				else
				{
					isError=true;	
				}				
			}
			else
			{
				isError=true;
			}
		}
		catch(Exception e)
		{
			isError = true;
			System.out.println("Exception "+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println(">>>>>>>>>>in finaly conn:"+conn);
				if(!isError)
				{
					conn.commit(); 
					System.out.println(">>>>>>>Transaction commit successfully");
					
				}
				else if(isError)
				{
					conn.rollback();
					System.out.println(">>>>>>>Transaction rollback successfully");
				}
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
	private String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
	{
		System.out.println(">>>>>>> In saving data method xmlString :"+xmlString);
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; 
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = "";
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateDistOrder :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateDistOrder :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}
}


