/*
 * Author:Wasim Ansari
 * Date:02-FEB-15
 * Request ID:D14IKAT004 (PO Wizard)
 */
package ibase.webitm.ejb.wms;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;

import java.net.InetAddress;
import java.rmi.RemoteException;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;

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

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Session Bean implementation class DDProductWizPosEJB
 */
@Stateless
public class DDPorderWizPosEJB extends ValidatorEJB implements DDPorderWizPosEJBRemote, DDPorderWizPosEJBLocal 
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	private String tranId = "";
	
	private String item_descr, item_parnt, item_ser, grp_code, item_type, phy_attrib_1, phy_attrib_2, phy_attrib_3, item_length, size_codes,
		item_width, item_height, price_list_dtl, item_gross_wt, item_parnt_desc, item_type_desc, itemser_descr, 
		descr, grp_code_desc, site_codes, color_codes, dimension_desc, supp_item_desc, item_barcode, item_category,
		img_path, item_sh_descr, long_desc, meta_desc, meta_keywords, meta_title;
	
    /**
     * Default constructor. 
     */
    public DDPorderWizPosEJB() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public String postSave(String xmlStringAll, String dcrId, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException 
	{
		String retString="";
		
		System.out.println("PostSave Action Called for PO Wizard:::");
		
		try 
		{
			retString = generatePurcOrder(xmlStringAll, xtraParams, "", conn);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		
		return retString;
	}
	
		
	public String generatePurcOrder(String xmlstring, String xtraParams, String forcedFlag, Connection conn) throws RemoteException,ITMException
	{
		System.out.println("Generating Purchase order");
		String confirmed = "";
		String purcOrder = "";
		String itemCode = "";
		String packCode = "";
		String siteCode = "";
		String dlvSiteCode = "";
		String ordSiteCode = "";
		String siteCodeBill = "";
		String unit = "";
		String suppCode = "";
		String sysDateStr = "";
		String tranCode = "";
		String retString = "";
		String loginEmpCode = "";
		String itemSer = "";
		String termTable="";
		String deptCode = "";
		String crTerm = "";
		String currCode = "";
		String dlvTerm = "";
		String address1 = "";
		String address2 = "";
		String city = "";
		String siteDescr = "";
		String remarks = "";
		String transMode = "";
		String acctCodeInv = "";
		String cctrCodeInv = "";
		String locCode = "";
		String acctCodeAp = "";
		String cctrCodeAp = "";
		String acctCodeDr = "";
		String cctrCodeDr = "";
		String acctCodeCr = "";
		String cctrCodeCr = "";
		String invAcctVal = "";
		String invAcctQcVal = "";
		String itemAcctDetr = "";
		String priceList = "";
		String pricelistClg="";
		String sql = "";
		String scacCode = "";
		String priceListStd = "";
		String postType = "";
		String tranType = ""; 
		String pOrder = "";
		String empCode = "";
		String dlvDate = "";
		String ordDate = "";
		Document dom = null;
		String chgTerm = "";
	
		String taxEnv = "";
		String taxClass = "";
		String taxChap = "";
		
		String termCode  = "";
		String termDescr = "";
		String printOpt  = "";
		String random = "";
		
		double rateStd = 0d;
	
		double rateClg = 0d; 
		String sql1 = "";
		Date currDate = null;
		Date dueDate = null;
		int purLeadTime = 0;
		SimpleDateFormat simpleDateFormat1 = null;
		
		boolean isError = false;
		int lineNo = 0;
		double quantity = 0 , rate = 0d;

		PreparedStatement pstmt = null,pstmt1 = null;
		PreparedStatement pstmtUpdate = null;
		ResultSet rs = null ,rs1 = null;	
		String errString = "";
		String loginSite = "";
		String userId = "";
		String asnNo = "";
		FinCommon finCommon = null;
		double exchRate = 0d;
		MasterStatefulLocal masterStatefulLocal = null;
		ITMDBAccessEJB itmdbAccess = new ITMDBAccessEJB();
		DistCommon distComm = new DistCommon();

		try
		{	
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			GenericUtility genericUtility = GenericUtility.getInstance();
			simpleDateFormat1 = new SimpleDateFormat(genericUtility.getApplDateFormat());
			finCommon = new FinCommon();
			currDate = new Date();
			System.out.println("XTRA PARAMS ["+xtraParams+"]");
			System.out.println("Getting XML String ["+xmlstring+"]");
			
			//loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			//userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			//loginSite = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode"));
	
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			Date sysDate = new Date();
			sysDateStr = sdf.format(sysDate);
			
			 String [] authencate = new String[2];
	         authencate[0] = "BASE";
	         authencate[1] = "";
			
			System.out.println("sysDate is :"+sysDate+" sysDate str is : "+sysDateStr);
			//siteCode  = "DDUK";//To be Removed.
			dom = genericUtility.parseString(xmlstring);
			
			Node detail1Node = dom.getElementsByTagName("Detail1").item(0);
			
			NodeList detail1List = detail1Node.getChildNodes();
			int detail1ListLen = detail1List.getLength();
			System.out.println("detail1ListLen =========================================="+detail1ListLen);
			for(int ctr = 0 ;ctr < detail1ListLen; ctr++)
			{
				Node childNode = detail1List.item(ctr);
				System.out.println("childNode " +childNode+"Node Value]");
				if(childNode == null || childNode.getNodeType() != childNode.ELEMENT_NODE)
				{
					continue;
				}
				
				System.out.println("childNodel " +childNode.getNodeName()+"Node Value]");
				
				if(childNode != null && "supp_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					suppCode = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "site_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					siteCode = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "tran_type".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					tranType = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "item_ser".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					itemSer = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "dept_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					deptCode = childNode.getFirstChild().getNodeValue();
					System.out.println("Department Code="+deptCode);
				}
				else if(childNode != null && "cr_term".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					crTerm = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "tran_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					tranCode = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "trans_mode".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					transMode = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "site_code__dlv".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					//siteCode = childNode.getFirstChild().getNodeValue();
					dlvSiteCode = childNode.getFirstChild().getNodeValue();
					System.out.println("Delivery="+dlvSiteCode);
				}
				else if(childNode != null && "site_code__ord".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					ordSiteCode = childNode.getFirstChild().getNodeValue();
					System.out.println("Order Site="+ordSiteCode);
				}
				else if(childNode != null && "pord_type".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					pOrder = childNode.getFirstChild().getNodeValue();
				}
				else if(childNode != null && "emp_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					empCode = childNode.getFirstChild().getNodeValue();
					System.out.println("EMPCODEIS="+empCode);
				}
				else if(childNode != null && "remarks".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					remarks = childNode.getFirstChild().getNodeValue();
					System.out.println("REMARKS="+remarks);
				}
				else if(childNode != null && "ord_date".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					ordDate = childNode.getFirstChild().getNodeValue();
					System.out.println("ORDDATE="+ordDate);
				}
				else if(childNode != null && "exch_rate".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					String exchVal = childNode.getFirstChild().getNodeValue();
					if(exchVal != null && exchVal.length() > 0)
					{
						exchRate = Double.parseDouble(exchVal);
					}
				}
				else if(childNode != null && "chg_user".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					userId = childNode.getFirstChild().getNodeValue();
					System.out.println("User Id="+userId);
				}
				else if(childNode != null && "chg_term".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					chgTerm = childNode.getFirstChild().getNodeValue();
					System.out.println("Change Term="+chgTerm);
				}
				else if(childNode != null && "term_table".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					termTable = childNode.getFirstChild().getNodeValue();
					System.out.println("Term Table="+termTable);
				}
				else if(childNode != null && "udf_str__2".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
				{
					random = childNode.getFirstChild().getNodeValue();
					System.out.println("Random Number="+random);
				}

				
			}
	
	
			sql = "SELECT SITE_CODE__ACCT, ADD1, ADD2, CITY, DESCR FROM SITE WHERE SITE_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			//pstmt.setString(1, siteCode);
			pstmt.setString(1, ordSiteCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				siteCodeBill = checkNull( rs.getString("SITE_CODE__ACCT") );
				address1 = checkNull( rs.getString("ADD1") );
				address2 = checkNull( rs.getString("ADD2") );
				city = checkNull( rs.getString("CITY") );
				siteDescr = checkNull( rs.getString("DESCR") );
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
	
			//remarks = "PO FROM WIZARD";
		/*	sql = "SELECT DEPT_CODE FROM EMPLOYEE WHERE EMP_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
		  //pstmt.setString(1, loginEmpCode);
			pstmt.setString(1, empCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				deptCode = checkNull(rs.getString( "DEPT_CODE" ));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;*/

			//sql = "SELECT CR_TERM, CURR_CODE, DLV_TERM, PRICE_LIST,PRICE_LIST__CLG FROM SUPPLIER WHERE SUPP_CODE = ? ";
			sql = "SELECT CR_TERM, CURR_CODE, DLV_TERM, PRICE_LIST,PRICE_LIST__CLG,TAX_ENV,TAX_CLASS,TAX_CHAP FROM SUPPLIER WHERE SUPP_CODE = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, suppCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				crTerm = checkNull(rs.getString( "CR_TERM" ));
				currCode = checkNull(rs.getString( "CURR_CODE" ));
				dlvTerm = checkNull(rs.getString( "DLV_TERM" ));
				priceList = checkNull(rs.getString( "PRICE_LIST" ));
				pricelistClg= checkNull(rs.getString( "PRICE_LIST__CLG" ));
				
				taxEnv= checkNull(rs.getString("TAX_ENV"));
				taxClass= checkNull(rs.getString("TAX_CLASS"));
				taxChap= checkNull(rs.getString("TAX_CHAP"));
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;

			
			String currCodeBase = "";
		
			sql = "SELECT A.CURR_CODE FROM FINENT A, SITE B WHERE B.FIN_ENTITY = A.FIN_ENTITY AND B.SITE_CODE = ? ";
			pstmt = conn.prepareStatement( sql );
			//pstmt.setString(1, loginSite );
			pstmt.setString(1, ordSiteCode );
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				currCodeBase = checkNull( rs.getString("CURR_CODE") );
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;

			StringBuffer xmlString= new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            xmlString.append("<DocumentRoot><description>Datawindow Root</description><group0><description>Group0 escription</description>");
            xmlString.append("<Header0>");
            xmlString.append("<description>Header0 members</description>");
            //xmlString.append("<objName><![CDATA[").append("porder_insert").append("]]></objName>");
            xmlString.append("<objName><![CDATA[").append("porder").append("]]></objName>");
            xmlString.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
            xmlString.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
            xmlString.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
            xmlString.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
            xmlString.append("<action><![CDATA[").append("SAVE").append("]]></action>");
            xmlString.append("<elementName><![CDATA[").append("").append("]]></elementName>");
            xmlString.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
            xmlString.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
            xmlString.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
            xmlString.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
            xmlString.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
            
            xmlString.append("<Detail1 dbID='' domID=\"1\" objName=\"porder\" objContext=\"1\">");
            xmlString.append("<attribute pkNames=\"purc_order:\" status=\"N\" updateFlag=\"A\" selected=\"N\" />");
            xmlString.append("<purc_order><![CDATA[").append("").append("]]></purc_order>");
            xmlString.append("<pord_type><![CDATA[").append(pOrder).append("]]></pord_type>");//tran type will be set
            xmlString.append("<ord_date><![CDATA[").append(ordDate).append("]]></ord_date>");
            //xmlString.append("<site_code__dlv><![CDATA[").append(siteCode).append("]]></site_code__dlv>");
           // xmlString.append("<site_code__ord><![CDATA[").append(siteCode).append("]]></site_code__ord>");
            xmlString.append("<site_code__dlv><![CDATA[").append(dlvSiteCode).append("]]></site_code__dlv>");
            xmlString.append("<site_code__ord><![CDATA[").append(ordSiteCode).append("]]></site_code__ord>");
            
            xmlString.append("<site_code__bill><![CDATA[").append(siteCodeBill).append("]]></site_code__bill>");
            xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
            
            xmlString.append("<confirmed><![CDATA[").append("Y").append("]]></confirmed>");
            xmlString.append("<conf_date><![CDATA[").append(sysDateStr).append("]]></conf_date>");
			xmlString.append("<emp_code__aprv><![CDATA[").append(empCode).append("]]></emp_code__aprv>");
            xmlString.append("<supp_code><![CDATA[").append(suppCode).append("]]></supp_code>");
            xmlString.append("<remarks><![CDATA[").append(remarks).append("]]></remarks>");
			xmlString.append("<status_date><![CDATA[").append(sysDateStr).append("]]></status_date>");
			xmlString.append("<tax_date><![CDATA[").append(sysDateStr).append("]]></tax_date>");
			xmlString.append("<dept_code><![CDATA[").append(deptCode).append("]]></dept_code>");
			xmlString.append("<emp_code><![CDATA[").append(empCode).append("]]></emp_code>");
			xmlString.append("<item_ser><![CDATA[").append(itemSer).append("]]></item_ser>");
			xmlString.append("<cr_term><![CDATA[").append(crTerm).append("]]></cr_term>");
			xmlString.append("<curr_code><![CDATA[").append(currCode).append("]]></curr_code>");
			xmlString.append("<curr_code__frt><![CDATA[").append(currCode).append("]]></curr_code__frt>");
			xmlString.append("<dlv_term><![CDATA[").append(dlvTerm).append("]]></dlv_term>");
			xmlString.append("<ord_amt><![CDATA[").append("0").append("]]></ord_amt>");
			//xmlString.append("<tax_amt><![CDATA[").append("0").append("]]></tax_amt>");
			//xmlString.append("<tot_amt><![CDATA[").append("0").append("]]></tot_amt>");
			xmlString.append("<frt_amt><![CDATA[").append("0").append("]]></frt_amt>");
			xmlString.append("<insurance_amt><![CDATA[").append("0").append("]]></insurance_amt>");
			xmlString.append("<adv_perc><![CDATA[").append("0").append("]]></adv_perc>");
			xmlString.append("<vouch_adv_amt><![CDATA[").append("0").append("]]></vouch_adv_amt>");
			xmlString.append("<accept_criteria><![CDATA[").append("N").append("]]></accept_criteria>");
			xmlString.append("<post_type><![CDATA[").append("S").append("]]></post_type>");
			xmlString.append("<site_add1><![CDATA[").append(address1).append("]]></site_add1>");
			xmlString.append("<site_add2><![CDATA[").append(address2).append("]]></site_add2>");
			xmlString.append("<city__site><![CDATA[").append(city).append("]]></city__site>");
			xmlString.append("<site_descr><![CDATA[").append(siteDescr).append("]]></site_descr>");
			xmlString.append("<tran_code><![CDATA[").append(tranCode).append("]]></tran_code>");
			xmlString.append("<trans_mode><![CDATA[").append(transMode).append("]]></trans_mode>");
			xmlString.append("<price_list><![CDATA[").append(priceList).append("]]></price_list>");
			xmlString.append("<price_list__clg><![CDATA[").append(pricelistClg).append("]]></price_list__clg>");
			xmlString.append("<exch_rate><![CDATA[").append(exchRate).append("]]></exch_rate>");
			xmlString.append("<curr_code__comm><![CDATA[").append(currCode).append("]]></curr_code__comm>");
			xmlString.append("<term_table><![CDATA[").append(termTable).append("]]></term_table>"); 
			xmlString.append("<frt_rate><![CDATA[").append(1).append("]]></frt_rate>");
			xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
			xmlString.append("<asn_no><![CDATA[").append("").append("]]></asn_no>");
		    xmlString.append("<udf_str__2><![CDATA[").append(random).append("]]></udf_str__2>");
			xmlString.append("</Detail1>");
			
			System.out.println("<!@#>seting status O xml " +xmlString.toString());

			double shipperSize = 0d, grossWeight = 0d, netWeight = 0d, tareWeight = 0d;

			int noArt = 0;
			
			String lineNoOrd = "";
	
			String lotNo = "";
			int domID = 0;
			NodeList detail3NodeList =dom.getElementsByTagName("Detail3");
			int detail3NodeListlen = detail3NodeList.getLength();
			for(int ctrH = 0; ctrH < detail3NodeListlen ; ctrH++)
			{
				NodeList childNodeList = detail3NodeList.item(ctrH).getChildNodes();
				
				int childNodeListlen = childNodeList.getLength();
				System.out.println("childNodeListlen ==================" +childNodeListlen);

				for(int ctrD = 0; ctrD < childNodeListlen ; ctrD++)
				{
					Node childNode = childNodeList.item(ctrD);
					
					if(childNode == null || childNode.getNodeType() != childNode.ELEMENT_NODE)
					{
						continue;
					}
					System.out.println("childNodeListlen ======childNode===========" +childNode.getNodeName());
					if(childNode != null && "item_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						itemCode = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "quantity".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						quantity = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					else if(childNode != null && "unit".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						unit = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "rate".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						rate = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					else if(childNode != null && "dlv_date".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						//dueDate = new Date(childNode.getFirstChild().getNodeValue());
						dlvDate = childNode.getFirstChild().getNodeValue();
						System.out.println("Delivery Date Final="+dlvDate);
					}
					else if(childNode != null && "pack_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						packCode = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "no_art".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						noArt = Integer.parseInt(childNode.getFirstChild().getNodeValue());
					}
					else if(childNode != null && "rate__clg".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						rateClg = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					else if(childNode != null && "std_rate".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						rateStd = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					else if(childNode != null && "loc_code".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						locCode = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "acct_code__dr".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						acctCodeDr = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "cctr_code__dr".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						cctrCodeDr = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "acct_code__cr".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						acctCodeCr = childNode.getFirstChild().getNodeValue();
					}
					else if(childNode != null && "cctr_code__cr".equalsIgnoreCase(childNode.getNodeName()) && childNode.getFirstChild() != null)
					{
						cctrCodeCr = childNode.getFirstChild().getNodeValue();
					}
					
				}
				domID++;
				xmlString.append("<Detail2 dbID=':' domID='" + domID + "' objName='porder' objContext='2'>");
                xmlString.append("<attribute pkNames='purc_order:line_no:' status='N' updateFlag='A' selected='N'/>");
                xmlString.append("<purc_order><![CDATA[").append("").append("]]></purc_order>");
				
				// pick right 3 char
				lineNoOrd = "   " + domID;
				lineNoOrd = lineNoOrd.substring( lineNoOrd.length()-3 );
				
                xmlString.append("<line_no><![CDATA[").append(lineNoOrd).append("]]></line_no>");
                xmlString.append("<status><![CDATA[").append("O").append("]]></status>");
				xmlString.append("<status_date><![CDATA[").append(sysDateStr).append("]]></status_date>");
              //xmlString.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
				xmlString.append("<site_code><![CDATA[").append(ordSiteCode).append("]]></site_code>");
                xmlString.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
                xmlString.append("<quantity><![CDATA[").append(quantity).append("]]></quantity>");
                xmlString.append("<quantity__stduom><![CDATA[").append(quantity).append("]]></quantity__stduom>");
                xmlString.append("<unit><![CDATA[").append(unit).append("]]></unit>");
                xmlString.append("<unit__std><![CDATA[").append(unit).append("]]></unit__std>");
                xmlString.append("<unit__rate><![CDATA[").append(unit).append("]]></unit__rate>");
                xmlString.append("<rate><![CDATA[").append( rate ).append("]]></rate>");
                xmlString.append("<discount><![CDATA[0]]></discount>");
               // xmlString.append("<tax_amt><![CDATA[0]]></tax_amt>");
               // xmlString.append("<tot_amt><![CDATA[0]]></tot_amt>");
                xmlString.append("<dlv_qty><![CDATA[0]]></dlv_qty>");
               // if(dueDate != null)
              //  {
                	//xmlString.append("<dlv_date><![CDATA["+simpleDateFormat1.format(dueDate)+"]]></dlv_date>");
                	xmlString.append("<dlv_date><![CDATA["+dlvDate+"]]></dlv_date>");
               // }
                xmlString.append("<rate__stduom><![CDATA[").append(rate).append("]]></rate__stduom>");
                xmlString.append("<pack_code><![CDATA[").append(packCode).append("]]></pack_code>");
               
                xmlString.append("<no_art><![CDATA[").append( noArt ).append("]]></no_art>");
                System.out.println("Rate clg value ["+rateClg+"]");
                xmlString.append("<rate__clg><![CDATA[").append(rateClg).append("]]></rate__clg>"); 
               
                xmlString.append("<std_rate><![CDATA[").append( rateStd ).append("]]></std_rate>");
                xmlString.append("<conv__qty_stduom><![CDATA[").append("1").append("]]></conv__qty_stduom>");
                xmlString.append("<conv__rtuom_stduom><![CDATA[").append("1").append("]]></conv__rtuom_stduom>");
                //xmlString.append("<req_date><![CDATA[").append(sysDateStr).append("]]></req_date>");
                xmlString.append("<req_date><![CDATA[").append(dlvDate).append("]]></req_date>");
                //xmlString.append("<loc_code><![CDATA[").append(locCode).append("]]></loc_code>");
                xmlString.append("<loc_code><![CDATA[").append(checkNull(locCode)).append("]]></loc_code>");
                xmlString.append("<acct_code__dr><![CDATA[").append(acctCodeDr).append("]]></acct_code__dr>");
                xmlString.append("<cctr_code__dr><![CDATA[").append(cctrCodeDr).append("]]></cctr_code__dr>");
                xmlString.append("<acct_code__cr><![CDATA[").append(acctCodeCr).append("]]></acct_code__cr>");
                xmlString.append("<cctr_code__cr><![CDATA[").append(cctrCodeCr).append("]]></cctr_code__cr>");
				xmlString.append("<operation><![CDATA[").append("0").append("]]></operation>");
				xmlString.append("<git_qty><![CDATA[").append("0").append("]]></git_qty>");
				xmlString.append("<adj_qty><![CDATA[").append("0").append("]]></adj_qty>");
				xmlString.append("<quantity__fc><![CDATA[").append("0").append("]]></quantity__fc>");
				
				xmlString.append("<tax_env><![CDATA[").append(taxEnv).append("]]></tax_env>");
				xmlString.append("<tax_class><![CDATA[").append(taxClass).append("]]></tax_class>");
				xmlString.append("<tax_chap><![CDATA[").append(taxChap).append("]]></tax_chap>");
				
                xmlString.append("</Detail2>");
	            System.out.println("xmlString For generation Purchase Order:: "+xmlString.toString());
			}
			
			domID = 0;
			lineNoOrd = "";
			
			sql = " select t.term_code,p.descr,p.print_yn from pur_term p, pur_term_table t where p.term_code=t.term_code and t.term_table = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, termTable);
			rs = pstmt.executeQuery();
			
			while(rs.next())
			{
				termCode  = checkNull(rs.getString("term_code"));
				termDescr = checkNull(rs.getString("descr"));
				printOpt  = checkNull(rs.getString("print_yn"));
				
				domID++;
				
				xmlString.append("<Detail3 dbID=':' domID='" + domID + "' objName='porder' objContext='3'>");
                xmlString.append("<attribute pkNames='purc_order:line_no:' status='N' updateFlag='A' selected='N'/>");
                xmlString.append("<purc_order><![CDATA[").append("").append("]]></purc_order>");
                
                lineNoOrd = "   " + domID;
				lineNoOrd = lineNoOrd.substring( lineNoOrd.length()-3 );
				
                xmlString.append("<line_no><![CDATA[").append(lineNoOrd).append("]]></line_no>");
                xmlString.append("<term_code><![CDATA[").append(termCode).append("]]></term_code>");
                xmlString.append("<descr><![CDATA[").append(termDescr).append("]]></descr>");
                xmlString.append("<print_opt><![CDATA[").append(printOpt).append("]]></print_opt>");
                xmlString.append("</Detail3>");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			
			
			xmlString.append("</Header0></group0></DocumentRoot>");
			System.out.println("xmlString For generation Purchase Order:: "+xmlString.toString());
            masterStatefulLocal = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local"); 
            
           // String [] authencate = new String[2];
           // authencate[0] = "BASE";
           // authencate[1] = "";
            
            //retString = masterStatefulLocal.processRequest( authencate, siteCode, true, xmlString.toString());
            if(xtraParams != null)
            {
            	xtraParams = getXtraParams(userId,ordSiteCode,empCode,conn);
            }
            String userInfo = getUserInfo(xtraParams);
            //retString = masterStatefulLocal.processRequest( authencate, ordSiteCode, true, xmlString.toString());
            retString = masterStatefulLocal.processRequest(userInfo, xmlString.toString(), true, conn); 
            //retString = masterStatefulLocal.processRequest( authencate, siteCode, true, xmlString.toString(),true,conn);
            
            System.out.println("retString....qqq:: "+retString);
            
			String autoConf = "";
			sql = "SELECT AUTO_CONFIRM FROM TRANSETUP WHERE TRAN_WINDOW = 'w_porder'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if( rs.next() )
			{	
				autoConf = checkNull(rs.getString("AUTO_CONFIRM"));
			}
			rs.close(); rs = null;
			pstmt.close(); pstmt = null;

			
			if ( retString.indexOf("Success") > -1 && retString.indexOf("<TranID>") > 0 )
			{
			    String tranIdPurcOrder = retString.substring( retString.indexOf("<TranID>")+8, retString.indexOf("</TranID>"));
				System.out.println("tranId is :"+tranIdPurcOrder);
				

				if( retString.indexOf("Success") != -1 )
				{
					
						
						sql = " UPDATE PORDER SET CONFIRMED = 'Y', EMP_CODE__APRV = ?, CONF_DATE = ?, POST_TYPE = 'S', PORD_TYPE = ?  WHERE PURC_ORDER = ? ";
						pstmtUpdate = conn.prepareStatement(sql);
					  //pstmtUpdate.setString(1, loginEmpCode);
						pstmtUpdate.setString(1, empCode);
						System.out.println("SYSDATE="+sysDateStr);
						sysDateStr = genericUtility.getValidDateString(sysDateStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
						System.out.println("SYSDATE2="+sysDateStr);
						pstmtUpdate.setTimestamp(2, Timestamp.valueOf( sysDateStr + " 00:00:00" ) );
					  //pstmtUpdate.setString(3, tranType);
						pstmtUpdate.setString(3, pOrder);
						pstmtUpdate.setString(4, tranIdPurcOrder);
						int updCnt = pstmtUpdate.executeUpdate();
						pstmtUpdate.close(); pstmtUpdate = null;
						System.out.println("updated records in PORDER : "+updCnt);
						errString = "";
					
					
				}
				
			}
			else
			{
				System.out.println("asn confirm error checking");
				return retString;
			}

			
		}
		catch(Exception e)
		{
			isError = true;
			errString = "ERROR";
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		System.out.println("errString from generatePorder =["+errString+"]");
		return errString;
	}
	
	/**
	 * get transaction id (parnt_code)
	 * @param conn
	 * @throws ITMException 
	 */
	private String getTransID( String windowName, Connection conn ) throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "", transId = "";

		try {
			selSql = "SELECT trim(to_char(prod_wiz_seq.nextval,'0000000000')) FROM DUAL";
			pstmt = conn.prepareStatement(selSql);
			
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				transId = rs.getString(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return transId;
		
		/*PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "";
		String tranId = "";
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues = "";

		 try
         {
			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, windowName );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
					keyString = rs.getString("KEY_STRING");
					keyCol = rs.getString("TRAN_ID_COL");
					tranSer = rs.getString("REF_SER");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer :"+tranSer);

			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +        "<tran_id></tran_id>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
         }
		catch (SQLException ex)
		{
			System.out.println("Exception ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e){}
		}
        return tranId;*/
	}
	public static java.util.Date addDays(java.util.Date date, int days) //added by Kunal on 01/09/12 
	{
		java.sql.Date calculatedDate = null;
		if (date != null) 
		{
			final GregorianCalendar calendar = new GregorianCalendar();
			calendar.setTime(date);
			calendar.add(Calendar.DATE,days);
			calculatedDate = new java.sql.Date(calendar.getTime().getTime());
		}

		return calculatedDate;
	}
	/**
	 * 
	 * @param dom
	 * @param attribute
	 * @param objContext
	 * @return
	 * @throws RemoteException
	 * @throws ITMException
	 */
	private String getObjNameFromDom( Document dom, String attribute, String objContext ) throws RemoteException,ITMException
	{
		NodeList detailList = null;
		Node currDetail = null;
		String objName = "";
		int detailListLength = 0;

		try
		{
			detailList = dom.getElementsByTagName("Detail"+objContext);
			detailListLength = detailList.getLength();
			for (int ctr = 0; ctr < detailListLength; ctr++)
			{
				currDetail = detailList.item(ctr);
				objName = currDetail.getAttributes().getNamedItem(attribute).getNodeValue();
			}
		}
		catch ( Exception e )
		{
			throw new ITMException(e);
		}
		System.out.println("objName =["+objName+"]");
		
		return objName;
	}
	
	public String checkNull(String input)
	{
		if (input == null || "null".equalsIgnoreCase(input))
		{
			input= "";
		}
		return input.trim();
	}
	
	@Override
	public String updateStatus(Document dom, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException 
	{
		return null;
	}
	
	private InitialContext getInitialContext() throws ITMException 
	{
		InitialContext ctx = null;
		try 
		{
			System.out.println("getInitialContext");
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());

		}
		catch (ITMException itme)
		{
			System.out.println("ITMException :StatelessItemChangeServlet :getInitialContext :==>");
			throw itme;
		}
		catch (Exception e) 
		{
			System.out.println("Exception :StatelessItemChangeServlet :getInitialContext :==>");
			throw new ITMException(e);
		}
		return ctx;
	}
	
	public String getUserInfo( String xtraParams )throws ITMException
	{
		StringBuffer userInfoStr = new StringBuffer();
		String userId = "";
		String loginEmpCode = "";
		String loginSiteCode = "";
		String entityCode = "";
		String profileId = "";
		String userType = "";
		
		String chgTerm = "";
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			entityCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"entityCode");
			profileId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"profileId");
			userType = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userType");
			
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			
			System.out.println("xtraParams  is @@@@@ " + xtraParams);

			userInfoStr.append("<UserInfo>");
			userInfoStr.append("<loginCode>").append("<![CDATA["+userId+"]]>").append("</loginCode>\r\n");
			userInfoStr.append("<empCode>").append("<![CDATA["+loginEmpCode+"]]>").append("</empCode>\r\n");
			userInfoStr.append("<siteCode>").append("<![CDATA["+loginSiteCode+"]]>").append("</siteCode>\r\n");
			userInfoStr.append("<entityCode>").append("<![CDATA["+entityCode+"]]>").append("</entityCode>\r\n");
			userInfoStr.append("<profileId>").append("<![CDATA["+profileId+"]]>").append("</profileId>\r\n");
			userInfoStr.append("<userType>").append("<![CDATA["+userType+"]]>").append("</userType>\r\n");
			
			userInfoStr.append("<remoteHost>").append("<![CDATA["+chgTerm+"]]>").append("</remoteHost>\r\n");
			userInfoStr.append("</UserInfo>");
		}
		catch ( Exception e )
		{
			throw new ITMException(e);
		}
		return userInfoStr.toString();
	}
	
	private ArrayList getTokenList(String tokenString, String delimiter) throws Exception
	{
		ArrayList returnList = null;
		if (tokenString != null && tokenString.length() > 0 && tokenString !="")
		{
			returnList = new ArrayList();
			if (delimiter.length() == 1)
			{
				while (tokenString.indexOf(delimiter) != -1)
				{
					int endIndex = tokenString.indexOf(delimiter);
					returnList.add(tokenString.substring(0, endIndex));
					tokenString = tokenString.substring(endIndex + 1, tokenString.length());
				}
				returnList.add(tokenString.substring(0, tokenString.length()));
			}
			else if ((delimiter.length() == 2) && (delimiter.equals("[]") || delimiter.equals("{}") || delimiter.equals("()")))
			{
				while (tokenString.indexOf(delimiter.substring(0, 1)) != -1)
				{
					int endIndex = tokenString.indexOf(delimiter.substring(1));
					returnList.add(tokenString.substring(1, endIndex));
					tokenString = tokenString.substring(endIndex + 1, tokenString.length());
				}
			}
		}
		return returnList;
	}
	public String getXtraParams( String loginCode, String siteCode,String empCode,Connection  conn)throws Exception
	{
		String remotehost = "";
		String entityCode = "";
		String profileId = "";
		String userType = "";
		String userLang = "";
		String userCountry = "";	
		StringBuffer xtraParamsBuff = new StringBuffer();
		
		String sql = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
			
		
		try
		{
				sql = "SELECT USR_LEV,USER_TYPE,ENTITY_CODE,PROFILE_ID,LOGGER_TYPE,USER_LANG,"+
					  "USER_COUNTRY,TRANS_DB, USER_THEME FROM USERS WHERE CODE = ? ";
				pstmt = conn.prepareStatement(sql);			
				pstmt.setString(1,loginCode);			
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					entityCode = rs.getString("ENTITY_CODE");
					profileId  = rs.getString("PROFILE_ID");
					userType   = rs.getString("USER_TYPE");
					userLang   = rs.getString("USER_LANG");
					userCountry= rs.getString("USER_COUNTRY");
				}			
				
				remotehost =  InetAddress.getLocalHost().getHostAddress();
				String XTRA_PARAMS_SEPARATOR = "~~";
				
				xtraParamsBuff.append("loginCode=" + loginCode);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginEmpCode=" + empCode);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginSiteCode=" + siteCode);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("entityCode=" + entityCode);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("profileId=" + profileId);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("userType=" + userType);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("runMode=I");
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_lang=" + userLang);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_country=" + userCountry);
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("charEnc=" + CommonConstants.ENCODING);
				
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("termId="+remotehost);
		
				String chgTerm = remotehost;
				if( chgTerm != null && chgTerm.length() > 15 )
				{
					chgTerm = chgTerm.substring(0, 15);
				}
				else if( chgTerm == null || chgTerm.length() == 0 )
				{
					chgTerm = remotehost;
				}
				xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("chgTerm=" + chgTerm );
				
				System.out.println("xtraParamsBuff ["+xtraParamsBuff+"]");
				
				
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return xtraParamsBuff.toString();
	}
}
