package ibase.webitm.ejb.mfg;

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

import org.w3c.dom.*;
import java.sql.Timestamp;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class RcptBackFlushPos extends ValidatorEJB implements  RcptBackFlushPosLocal ,RcptBackFlushPosRemote //SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate()
	{
	}

	public void ejbPassivate()
	{
	}*/

	public String postSave() throws RemoteException,ITMException
	{
		return "";
	}


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

	private String executePostSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, String windowName, Connection conn)throws RemoteException,ITMException
	{
		Statement stmt = null;
		PreparedStatement pstmt = null;  // 24/01/11 - Chandni Shah
		ResultSet rs = null;
		String siteCodeReq = "", itemCode = "", lineNo = "",locCode = "", lotNo = "", lotSl = "",locCodeInsp="";
		String sql = "", line = "", tranType = "", errString = "";
		String sumQtyDet = "" ; // 24/01/11 - Chandni Shah
		double qtyDoc = 0d;  // 24/01/11 - Chandni Shah
		// 27/01/11 - Chandni Shah
		String backflushType = "" , locCodeDet = "" ; 
		Timestamp mfgDate = null; 
		Timestamp expDate = null; 
		//
		HashMap strAllocate = null;
		double quantity = 0d;
		int updateCnt = 0, retVal  = 0;
		java.sql.Date tranDate = null;
		String updateStatus = "",quantityStr = "",tranId = "";
		NodeList hdrDom = null;
		Node currDetail = null;
		InvAllocTraceBean invAllocTrace = new InvAllocTraceBean();
		String qcReqd = "N", lotNoDet = "";
		String lotSlDet = "",itemCodeHdr = "";//added by Kunal on 19/10/12
		try
		{
			stmt = conn.createStatement();

			tranDate = new java.sql.Date(System.currentTimeMillis());
			System.out.println("\n tranDate :"+tranDate);

			hdrDom = dom.getElementsByTagName("Detail1");
			tranType = GenericUtility.getInstance().getColumnValueFromNode("tran_type",hdrDom.item(0));
			siteCodeReq = GenericUtility.getInstance().getColumnValueFromNode("site_code",hdrDom.item(0));
			tranId = GenericUtility.getInstance().getColumnValueFromNode("tran_id",hdrDom.item(0));
			qcReqd = GenericUtility.getInstance().getColumnValueFromNode("qc_reqd",hdrDom.item(0));
			itemCodeHdr = GenericUtility.getInstance().getColumnValueFromNode("item_code",hdrDom.item(0));


			System.out.println("\n tranId :"+tranId);
			// 24/01/11 - Chandni Shah

			sql = "SELECT B.SUM_QTY_DET,A.BACKFLUSH_TYPE "
					+ " FROM RECEIPT_BACKFLUSH A,BACKFLUSH_TYPE B "
					+" WHERE A.BACKFLUSH_TYPE = B.BACKFLUSH_TYPE "
					+" AND  TRAN_ID = ? " ; 
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				sumQtyDet = rs.getString("sum_qty_det");
				backflushType = rs.getString("backflush_type");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if ("Y".equalsIgnoreCase(sumQtyDet))
			{
				sql = " select sum ( (case when CONV_QTY_DOC is null or CONV_QTY_DOC <= 0 then 1 else CONV_QTY_DOC end) * quantity  )as qty_doc "
						+" from receipt_backflush_det "
						+" where tran_id = ? "  ;
				pstmt =  conn.prepareStatement(sql);
				pstmt.setString(1,tranId);
				rs = pstmt.executeQuery();

				if(rs.next())
				{
					qtyDoc = rs.getDouble(1);
				}

				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				sql = " update  receipt_backflush  "
						+" set quantity = ? "
						+" where tran_id = ? ";
				pstmt =  conn.prepareStatement(sql);
				pstmt.setDouble(1,qtyDoc);
				pstmt.setString(2,tranId);
				int upd = pstmt.executeUpdate();

				pstmt.close();
				pstmt = null;
			}
			// 27/01/11 - Chandni Shah
			if ("C".equalsIgnoreCase(backflushType) || "S".equalsIgnoreCase(backflushType) || "R".equalsIgnoreCase(backflushType)) //change done by Kunal on 19/10/12 add cond. for 'S' and 'R'
			{
				sql = " select s.mfg_date,s.exp_date,r.loc_code, r.lot_no,r.item_code ,r.lot_sl from "
						+" receipt_backflush_det r , stock s "
						+" where r.item_code = s.item_code "
						+" and r.site_code = s.site_code "
						+" and r.loc_code = s.loc_code "
						+" and r.lot_no = s.lot_no "
						+" and r.lot_sl = s.lot_sl "
						+" and r.tran_id = ? " ;

				pstmt =  conn.prepareStatement(sql);
				pstmt.setString(1,tranId);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					mfgDate = rs.getTimestamp ("mfg_date") ; 
					expDate = rs.getTimestamp ("exp_date");
					locCodeDet = rs.getString ("loc_code");
					lotNoDet = rs.getString ("lot_no");
					itemCode = rs.getString ("item_code");
					lotSlDet = rs.getString ("lot_sl"); //added by Kunal on 19/10/12
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				if ("C".equalsIgnoreCase(backflushType) || "S".equalsIgnoreCase(backflushType) )//added by Kunal on 19/10/12  
				{
					if ("Y".equals(qcReqd) )
					{

						//added by cpatil on 20-AUG-12 [MF2ESUN002] as per suggestion -- start

						sql = "select loc_code__insp from siteitem where site_code = ? and item_code = ? " ;
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,siteCodeReq);
						pstmt.setString(2,itemCodeHdr);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							locCodeInsp = rs.getString("loc_code__insp") ; 
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if( locCodeInsp == null || locCodeInsp.trim().length() == 0 )
						{
							locCodeInsp = locCodeDet.trim() + "Q";
						}
						System.out.println("@@@@@ loc_code:"+locCodeInsp);
						//added by cpatil on 20-AUG-12 [MF2ESUN002]as per suggestion --  end

						sql = " update  receipt_backflush  "
								+" set mfg_date = ?  ,  "
								+" exp_date = ?  ,  "
								+" loc_code = ? ,"
								+" lot_no = ?  ,"
								+ " lot_sl = ? " 
								+" where tran_id = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setTimestamp(1,mfgDate);
						pstmt.setTimestamp(2,expDate);
						pstmt.setString(3,locCodeInsp);   // modify by cpatil on 20-AUG-12 as per suggestion
						pstmt.setString(4,lotNoDet);  //added by Kunal on 25/10/12 as per Rawtani Sir  instruction 
						pstmt.setString(5,lotSlDet);//added by Kunal on 25/10/12 as per Rawtani Sir  instruction
						pstmt.setString(6,tranId);
					}
					else
					{
						sql = " update  receipt_backflush  "
								+" set mfg_date = ?  ,  "
								+" exp_date = ?  ,  "
								+" loc_code = ?, "
								+ " lot_no = ?  ,"
								+ " lot_sl = ? " //added by Kunal on 19/10/12
								+" where tran_id = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setTimestamp(1,mfgDate);
						pstmt.setTimestamp(2,expDate);
						pstmt.setString(3,locCodeDet);
						pstmt.setString(4,lotNoDet);
						pstmt.setString(5,lotSlDet);
						pstmt.setString(6,tranId);

					}
				}
				else
				{
					sql = " update  receipt_backflush  "
							+" set mfg_date = ?  ,  "
							+" exp_date = ?   "
							+" where tran_id = ? ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setTimestamp(1,mfgDate);
					pstmt.setTimestamp(2,expDate);
					pstmt.setString(5,tranId);

				}
				int upd = pstmt.executeUpdate();

				pstmt.close();
				pstmt = null;
			}
			currDetail = getCurrentDetailFromDom(dom,domID);
			updateStatus = getCurrentUpdateFlag(currDetail);

			System.out.println("updateStatus :: "+updateStatus);

			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);

				//				if (tranType.equals("I"))
				//				{

				if (quantity > 0)
				{
					line = "   " + lineNo;
					System.out.println("line  :"+line);
					strAllocate = new HashMap();
					strAllocate.put("tran_date",tranDate);
					strAllocate.put("ref_ser","R-BFS");
					strAllocate.put("ref_id",tranId);
					strAllocate.put("ref_line",line.substring(line.length()-3));
					strAllocate.put("site_code",siteCodeReq);
					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",windowName);

					errString = invAllocTrace.updateInvallocTrace(strAllocate, conn);
					System.out.println("errString ::: " + errString);

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

				throw new ITMException(e);
			}
			return errString;
		}
		//return errString;
	}

	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;
	}
}