package ibase.webitm.ejb.dis;

import java.rmi.RemoteException;
import java.util.*;
import java.sql.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import org.w3c.dom.*;

import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.InvAllocTraceBean;
import ibase.system.config.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import javax.ejb.Stateless; // added for ejb3


//public class DistIssuePosEJB extends ValidatorEJB implements SessionBean
@Stateless // added for ejb3
public class DistIssuePos extends ValidatorEJB implements DistIssuePosLocal, DistIssuePosRemote
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate() 
	{
	}

	public void ejbPassivate() 
	{
	}*/

    public String postSaveRec()throws RemoteException,ITMException
	{
		return "";
	}
	
	public String postSaveRec(String xmlString1,String domId,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		Document dom = null;
		System.out.println("DistIssuePosEJB called");
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				executepostSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}			
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :DistIssuePosEJB ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return "";
	}

	private String executepostSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		Statement stmt = null, stmt1 = null;
		ResultSet rs = null, rs1 = null, rs2 = null;
		PreparedStatement pstmt = null;
		String siteCode = "", itemCode = "", lineNo = "",locCode = "", lotNo = "", lotSl = "";
		String sql = "", line = "", stockOpt = "", sqlItem = "";
		HashMap strAllocate = new HashMap();
		double quantity = 0d;
		int retVal = 0;
		java.sql.Date tranDate = null;
		DistStkUpdLocal distStkUpd = null;
		Node currDetail = null;
		NodeList hdrDom = null;
		String errString = "";
		String updateStatus = "",quantityStr = "",tranId = "";
		try
		{
			stmt = conn.createStatement();
			stmt1 = conn.createStatement();
			distStkUpd = getComponent("DistStkUpd");

			tranDate = new java.sql.Date(System.currentTimeMillis());
			System.out.println("\n tranDate :"+tranDate);
			
			hdrDom = dom.getElementsByTagName("Detail1");
			siteCode = GenericUtility.getInstance().getColumnValueFromNode("site_code",hdrDom.item(0));
			tranId = GenericUtility.getInstance().getColumnValueFromNode("tran_id",hdrDom.item(0));

			currDetail = getCurrentDetailFromDom(dom,domID);
			updateStatus = getCurrentUpdateFlag(currDetail);

			if (currDetail != null && !updateStatus.equalsIgnoreCase("D"))
			{
				lineNo = GenericUtility.getInstance().getColumnValueFromNode("line_no",currDetail);
				itemCode = GenericUtility.getInstance().getColumnValueFromNode("item_code",currDetail);
				locCode = GenericUtility.getInstance().getColumnValueFromNode("loc_code",currDetail);
				lotNo = GenericUtility.getInstance().getColumnValueFromNode("lot_no",currDetail);
				lotSl = GenericUtility.getInstance().getColumnValueFromNode("lot_sl",currDetail);
				quantityStr = GenericUtility.getInstance().getColumnValueFromNode("quantity",currDetail);
				quantity = Double.parseDouble(quantityStr);
				line = "   " + lineNo;
				line = line.substring(line.length()-3);				
				
				if (lotNo == null || lotNo.trim().length() == 0)
				{
					lotNo = "               ";
				}
				if (lotSl == null || lotSl.trim().length() == 0)
				{
					lotSl = "     ";
				}

				sqlItem = "SELECT STK_OPT FROM SITEITEM WHERE ITEM_CODE = '"+itemCode+"' "
					 +"AND SITE_CODE = '"+siteCode+"'";
				System.out.println("The select sql sqlItem:"+sqlItem);
				rs1 = stmt1.executeQuery(sqlItem);
				if (rs1.next())
				{
					stockOpt = rs1.getString(1);
					System.out.println("stockOpt :"+stockOpt);
				}
				if (stockOpt == null)
				{
					sqlItem = "SELECT STK_OPT FROM ITEM WHERE ITEM_CODE ='"+itemCode+"'";
					System.out.println("The select sqlItem :"+sqlItem);
					rs2 = stmt1.executeQuery(sqlItem);
					if (rs2.next())
					{
						stockOpt = rs2.getString(1);
						System.out.println("stockOpt :"+stockOpt);
					}
				}
				if (!stockOpt.equalsIgnoreCase("0"))
				{
					strAllocate.put("tran_date",tranDate);
					strAllocate.put("ref_ser","D-ISS");
					strAllocate.put("ref_id",tranId);
					strAllocate.put("ref_line",line.substring(line.length()-3));					
					strAllocate.put("site_code",siteCode);
					strAllocate.put("item_code",itemCode);
					strAllocate.put("loc_code",locCode);
					strAllocate.put("lot_no",lotNo);
					strAllocate.put("lot_sl",lotSl);
					strAllocate.put("alloc_qty",new Double(quantity)); 
					strAllocate.put("chg_user",GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
					strAllocate.put("chg_term",GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"termId"));
					strAllocate.put("chg_win","W_DIST_ISSUE");
					
					System.out.println("Calling DistStkUpdEJB.....");				
					//if (distStkUpd.updAllocTrace(strAllocate) > 0)
					/*Changed by HATIM on 13/01/2006*/
					InvAllocTraceBean invAllocTrace = new InvAllocTraceBean();
					
					/*if (distStkUpd.updAllocTrace(strAllocate, conn) > 0)
					{
						System.out.println("distStkUpd.UpdAllocTrace(HashMap, Connection) : Sucessuful!");
					}*/
					
					errString = invAllocTrace.updateInvallocTrace(strAllocate, conn);
					System.out.println("errString ::: " + errString);

					if (errString == "")
					{
						System.out.println("invAllocTrace.updateInvallocTrace : Sucessuful!");
					}
					invAllocTrace = null;
					/*END*/
				}
			}//while end
		}//try end
		catch (SQLException sqx)
		{
			System.out.println("The SQLException occurs in DistIssuePostSaveEJB :"+sqx);
			sqx.printStackTrace();
			throw new ITMException(sqx);
		}
		catch(Exception e)
		{
			System.out.println("The SQLException occurs in DistIssuePostSaveEJB  :"+e);			
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if(stmt1 != null)
				{
					stmt1.close();
					stmt1 = null;
				}			
			}
			catch(Exception e)
			{
				System.err.println("Exception :DistIssuePosEJB ::\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return "";
	}

	private Node getCurrentDetailFromDom(Document dom,String domId)
	{
		NodeList detailList = null;
		Node currDetail = null,reqDetail = null;
		String currDomId = "";
		int	detailListLength = 0;

		detailList = dom.getElementsByTagName("Detail2");
		detailListLength = detailList.getLength();
		for (int ctr = 0;ctr < detailListLength;ctr++)
		{
			currDetail = detailList.item(ctr);
			currDomId = currDetail.getAttributes().getNamedItem("domID").getNodeValue();
			if (currDomId.equals(domId))
			{
				reqDetail = currDetail;
				break;
			}			
		}
		return reqDetail;
	}

	private String getCurrentUpdateFlag(Node currDetail)
	{
		NodeList currDetailList = null;
		String updateStatus = "",nodeName = "";
		int currDetailListLength = 0;

		currDetailList = currDetail.getChildNodes();
		currDetailListLength = currDetailList.getLength();
		for (int i=0;i< currDetailListLength;i++)
		{
			nodeName = currDetailList.item(i).getNodeName();
			if (nodeName.equalsIgnoreCase("Attribute"))
			{
				updateStatus = currDetailList.item(i).getAttributes().getNamedItem("updateFlag").getNodeValue();
				break;
			}
		}
		return updateStatus;		
	}	

	/*private DistStkUpd getComponent(String componentName)throws Exception
    {
		DistStkUpd comp = null;
        try
        {
			System.out.println("Looking For Component.... :: " + componentName);
			AppConnectParm appConnect = new AppConnectParm();
			java.util.Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			DistStkUpdHome distStkUpdHome = (DistStkUpdHome)ctx.lookup(componentName);
			comp = distStkUpdHome.create();
			System.out.println(componentName+" Found.....");			
        }
        catch(Exception e)
        {
			throw e;
        }
		return comp;
	}*/
	private DistStkUpdLocal getComponent(String componentName)throws Exception
    {
		DistStkUpdLocal comp = null;
        try
        {
			System.out.println("Looking For Component.... :: " + componentName);
			AppConnectParm appConnect = new AppConnectParm();
			java.util.Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			 comp = (DistStkUpdLocal)ctx.lookup("ibase/DistStkUpd/local"); // for ejb3
			//comp = distStkUpdHome.create();
			System.out.println(componentName+" Found.....");			
        }
        catch(Exception e)
        {
			throw e;
        }
		return comp;
	}
}