/* This file is Cteated it incorporate the Pre Save logic from Window
 * Gulzar 08/09/06
 */
package ibase.webitm.ejb.dis;

import javax.ejb.*;
import java.sql.*;
import java.rmi.RemoteException;
import java.util.*;

import org.w3c.dom.*;
import javax.naming.InitialContext;

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


//public class SReturnPrsEJB extends ValidatorEJB implements SessionBean
@Stateless // added for ejb3
public class SReturnPrs extends ValidatorEJB implements SReturnPrsLocal, SReturnPrsRemote
{
	/*
	public void ejbCreate() throws RemoteException, CreateException
	{
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String preSaveRec() throws RemoteException, ITMException
	{
		return "";
	}
	public String preSaveRec(String xmlString1, String domId, String objContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		System.out.println("SReturnPrsEJB Called");
		Document dom = null;
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				executepreSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :SReturnPrsEJB :preSaveRec(): " + e.getMessage()+ ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return "";
	}
	private String executepreSaveRec(Document dom, String domID, String ObjContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		String siteCode = "", itemCode = "", lineNo = "",locCode = "", lotNo = "", lotSl = "";
		String tranId = "", updateStatus = "", qtyStr = "";
		String sqlStr = "", retFlg = "";
		double quantity = 0d;
		java.util.Date tranDate = null;
		DistStkUpdLocal distStkUpd = null;
		NodeList hdrDom = null;
		Node currDetail = null;
		Statement stmt = null;
		ResultSet rs = null;
		HashMap strAllocate = new HashMap();
		try
		{
			distStkUpd = getComponent("DistStkUpd");
			tranDate = new java.sql.Date(System.currentTimeMillis());
			System.out.println("\n tranDate :"+tranDate);
			hdrDom = dom.getElementsByTagName("Detail1");
			tranId = GenericUtility.getInstance().getColumnValueFromNode("tran_id",hdrDom.item(0));
			siteCode = GenericUtility.getInstance().getColumnValueFromNode("site_code",hdrDom.item(0));
			System.out.println("\n tranId :"+tranId);
			System.out.println("\n siteCode :"+siteCode);
			currDetail 	= getCurrentDetailFromDom(dom,domID);
			updateStatus = getCurrentUpdateFlag(currDetail);
			
			if (currDetail != null && !updateStatus.equalsIgnoreCase("A"))
			{
				stmt = conn.createStatement();
				retFlg = GenericUtility.getInstance().getColumnValueFromNode("ret_rep_flag",currDetail);
				
				if (retFlg.equalsIgnoreCase("P"))
				{
					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);
				
					sqlStr = "SELECT QUANTITY FROM SRETURNDET WHERE TRAN_ID = '"+tranId+"'" +
					" AND LINE_NO = "+lineNo+""; //Omited the single quotes as it is not working in DB2 //Gulzar 09-01-07
					System.out.println("sqlStr :: " + sqlStr);
					rs = stmt.executeQuery(sqlStr);
					if(rs.next())
					{
						qtyStr = rs.getString(1);
					}
					lineNo ="   " + lineNo;
					System.out.println("Line No : lineNo := "+lineNo);
					quantity = Double.parseDouble(qtyStr);
					strAllocate.put("tran_date",tranDate);
					strAllocate.put("ref_ser","S-RET");
					strAllocate.put("ref_id",tranId);
					strAllocate.put("ref_line",lineNo.substring(lineNo.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(-1*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_SALESRETURN");
					
					if (distStkUpd.updAllocTrace(strAllocate, conn) > 0) 
					{
						System.out.println("distStkUpd.UpdAllocTrace(HashMap, Connection) : Sucessuful!");
					}
				}
			}
		}
		catch (SQLException sqe)
		{
			System.out.println("The SQLException occurs in SReturnPrsEJB :"+sqe);
			sqe.printStackTrace();
			throw new ITMException(sqe);
		}
		catch(Exception e)
		{
			System.out.println("The Exception occurs in SReturnPrsEJB :"+e);			
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :SReturnPrsEJB :\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;
	}
}
