package ibase.webitm.ejb.dis;

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

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


//public class StockTransferPosEJB extends ValidatorEJB implements SessionBean
@Stateless // added for ejb3
public class StockTransferPos extends ValidatorEJB implements StockTransferPosLocal, StockTransferPosRemote
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("ejbCreate() method calling........");
	}
	public void ejbRemove()
	{
		System.out.println("ejbRemeove() method calling........");
	}
	public void ejbActivate() 
	{
		System.out.println("ejbActivate() method calling........");
	}
	public void ejbPassivate() 
	{
		System.out.println("ejbPassivate() method calling........");
	}*/
	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("StockTransferPosEJB 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 :StockTransferPosEJB ::" + 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
	{

		HashMap hashMap = new HashMap(); 
		String lineNo = "", tranId = "", tranSer = "XRFX", line = "", updateStatus = "";
		String siteCode = "", itemCode = "", quantity = "", locCode = "", lotNo = "", lotSl = "";
		DistStkUpdLocal distStkUpd = null;
		NodeList hdrDom = null;
		Node currDetail = null;
		try
		{
			System.out.println("objContext =[" + objContext + "]");
			System.out.println("domID =[" + domID + "]");

			distStkUpd = getComponent("DistStkUpd");
			
			hdrDom = dom.getElementsByTagName("Detail1");
			siteCode = GenericUtility.getInstance().getColumnValueFromNode("site_code",hdrDom.item(0));
			tranId = GenericUtility.getInstance().getColumnValueFromNode("tran_id",hdrDom.item(0));
			System.out.println("tran_id : " + tranId);

			//currDetail = getCurrentDetailFromDom(dom,domID); Commented by gulzar on 12/24/2011
			currDetail = getCurrentDetailFromDom( dom, domID, objContext );//Change added by gulzar on 12/24/2011
			updateStatus = getCurrentUpdateFlag(currDetail);

			if (currDetail != null && !updateStatus.equalsIgnoreCase("D"))
			{
				itemCode = GenericUtility.getInstance().getColumnValueFromNode("item_code",currDetail);
				locCode = GenericUtility.getInstance().getColumnValueFromNode("loc_code__fr",currDetail);
				lotNo = GenericUtility.getInstance().getColumnValueFromNode("lot_no__fr",currDetail);
				lotSl = GenericUtility.getInstance().getColumnValueFromNode("lot_sl__fr",currDetail);
				quantity = GenericUtility.getInstance().getColumnValueFromNode("quantity",currDetail);
				lineNo = GenericUtility.getInstance().getColumnValueFromNode("line_no",currDetail);
				System.out.println("lineNo :"+lineNo+" itemCode :"+itemCode+" locCodeFr :"+locCode+" lotNoFr :"+lotNo+" lotSlFr :"+lotSl+" quantity :"+quantity);
				String stlOption = chkStockOption(itemCode, siteCode);
				System.out.println("stlOption  :"+stlOption);
				if (!stlOption.equals("0"))
				{
					if (quantity == null)
					{
						quantity = "0.000";
					}
					hashMap.put("tran_date", new java.sql.Date(System.currentTimeMillis()));
					hashMap.put("ref_ser",tranSer);
					hashMap.put("ref_id", tranId);
					hashMap.put("ref_line", lineNo);
					hashMap.put("item_code", itemCode);
					hashMap.put("site_code", siteCode);
					hashMap.put("loc_code",locCode);
					hashMap.put("lot_no",lotNo);
					hashMap.put("lot_sl",lotSl);
					hashMap.put("alloc_qty", new Double(quantity.trim().length() == 0?"0":quantity));
					hashMap.put("chg_win","W_STOCK_TRANSFER_MULTI");
					hashMap.put("chg_user", GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams, "loginCode"));
					hashMap.put("chg_term", GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams, "termId"));
					//Calling DistStkUpdEJB
					System.out.println("Calling DistStkUpdEJB.....");				
					if (distStkUpd.updAllocTrace(hashMap, conn) > 0)
					{
						System.out.println("distStkUpd.UpdAllocTrace(HashMap, Connection) : Sucessuful!");
					}
				}//end if
			}//end if
		}//end try
		catch(Exception e)
		{
			System.out.println("Exception : StockTransferPosEJB : actionHandler :" +e.getMessage());
			throw new ITMException(e);
		}
		return "";
	}

	private String chkStockOption(String itemCode, String siteCode)throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "", stkOption = "";
		ConnDriver connDriver = new ConnDriver();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			stmt = conn.createStatement();
			sql = "SELECT CASE WHEN STK_OPT IS NULL THEN 'N' ELSE STK_OPT END "
				 +"FROM SITEITEM "
				 +"WHERE ITEM_CODE = '"+itemCode+"' "
				 +"AND SITE_CODE = '"+siteCode+"' ";
			System.out.println("sql :"+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				stkOption = rs.getString(1);
			}
			if (stkOption == null || stkOption.equals("N"))
			{
				sql = "SELECT CASE WHEN STK_OPT IS NULL THEN '0' ELSE STK_OPT END "
					 +"FROM ITEM "
					 +"WHERE ITEM_CODE = '"+itemCode+"'";
				System.out.println("sql :"+sql);
				rs = stmt.executeQuery(sql);
				if (rs.next())
				{
					stkOption = rs.getString(1);
				}
			}//end if
			System.out.println("stkOption :"+stkOption);
		}//end try
		catch(SQLException e)
		{
			System.out.println("Exception : StockTransferPosEJB : actionStock " +e.getMessage());
			throw new ITMException(e);
		}
		catch(Exception e)
		{
			System.out.println("Exception : StockTransferPosEJB : actionHandler :" +e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (stmt != null)
				{
					stmt.close();
					stmt = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("The Exception occurs in StockTransferPosEJB "+e);	
			}
		}
		return stkOption;
	}
	//private Node getCurrentDetailFromDom(Document dom,String domId)//Commented by gulzar on 12/24/2011
	private Node getCurrentDetailFromDom( Document dom, String domId, String objContext ) //changed added by gulzar on 12/24/2011
	{
		NodeList detailList = null;
		Node currDetail = null,reqDetail = null;
		String currDomId = "";
		int	detailListLength = 0;

		//detailList = dom.getElementsByTagName("Detail2");//Commented by gulzar on 12/24/2011
		detailList = dom.getElementsByTagName("Detail"+objContext);//change added by gulzar on 12/24/2011
		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;
	}*/
	// for ejb3 
	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;
	}
}