package ibase.webitm.ejb.mfg;

import java.sql.*;
import java.rmi.RemoteException;
import java.util.*;
import org.w3c.dom.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.*;
import ibase.webitm.utility.*;
import ibase.utility.*;
import ibase.webitm.ejb.*;
import java.text.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class WORPostSave extends ValidatorEJB implements  WORPostSaveLocal , WORPostSaveRemote //SessionBean
{
	/*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
	{
		System.out.println("WORPostSaveEJB Called............!");
		System.out.println("xml............!"+xmlString1);
		String saveRec = "";
		Document dom = null;
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				saveRec = executepostSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :WORPostSaveEJB :postSaveRec(): " + e.getMessage()+ ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return saveRec;
	}
    private String executepostSaveRec(Document dom, String domID, String ObjContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		String trantype = "", workorder = "", itemcode = "", sitecode = "" ,lotno = "";
		String ordertypeT = "",genlotnoT = "", sql = "",sql1 = "",keyT = "";
		NodeList hdrDom = null;
		Node currDetail = null;
		Statement stmt = null;
		ResultSet rs = null;
	    String ls_fglotnoon = "",ls_setfg = "";
		String ls_win = "fg_lotno";
		String tranIdG = "",sqlUpd = "";
		String errString = "";
		String errCode = "";
		String userId = ""; 
		boolean lb_nositeitem = false;
		int  updCnt = 0;

	    GenericUtility genericUtility = GenericUtility.getInstance();
		userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		try
		{	userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			currDetail 	= getCurrentDetailFromDom(dom,domID);
			if (currDetail != null)
			{	stmt = conn.createStatement();
				trantype	= genericUtility.getColumnValueFromNode("tran_type",currDetail);
				workorder	= genericUtility.getColumnValueFromNode("work_order",currDetail);
				itemcode	= genericUtility.getColumnValueFromNode("item_code",currDetail);
				sitecode	= genericUtility.getColumnValueFromNode("site_code",currDetail);
				lotno	= genericUtility.getColumnValueFromNode("lot_no",currDetail);
				workorder = workorder.trim();
				sitecode  = sitecode.trim();
                System.out.println("trantype :: "+trantype);
				System.out.println("workorder ::"+workorder);
				System.out.println("itemcode :: "+itemcode);
				System.out.println("sitecode :: "+sitecode);
				System.out.println("lotno ::    "+lotno);
				try
		         {      
						sql = "select ORDER_TYPE from workorder where WORK_ORDER = '"+workorder+"'";
						System.out.println("sql ....:"+sql);
						rs = stmt.executeQuery(sql);
						if(!rs.next())
						{
							System.out.println("No record found for ORDER_TYPE from workorder where WORK_ORDER = '"+workorder+"'");
							
						}
						else
						{
							ordertypeT = rs.getString(1);
							ordertypeT = ordertypeT.trim();
							System.out.println("ordertypeT..."+ordertypeT);
						}
						rs.close();
			            rs = null;
						
				 }
				catch(Exception e)
				 {
					System.out.println("Exception in ..WORK_ORDER....");
					e.printStackTrace();
				 }
				try
		         {     
					    sql1 = "SELECT CASE WHEN generate_lot_no IS NULL THEN '0' ELSE generate_lot_no END"
						+" from siteitem where site_code = '"+sitecode+"' and item_code = '"+itemcode+"' ";
					    System.out.println("sql1 ....:"+sql1);
						rs = stmt.executeQuery(sql1);
						if(!rs.next())
						{
							lb_nositeitem = true;
							System.out.println("lb_nositeitem........."+lb_nositeitem);
							System.out.println("No record found for generate_lot_no");
						}
						else
						{
							genlotnoT = rs.getString(1);
							System.out.println("genlotnoT..."+genlotnoT);
						}
						rs.close();
			            rs = null;
						
				 }
				 catch(Exception e)
					  {
						System.out.println("Exception in ..genlotnoT....");
						e.printStackTrace();
					  }
		         System.out.println("count=>"+("RFP".indexOf(ordertypeT)));
				 if (!trantype.equalsIgnoreCase("B")) 
					{
						ls_setfg= getDisparams("999999","FG_LOTNO",conn);
						System.out.println("ls_setfg..."+ls_setfg);
                        ls_fglotnoon = getmfgparams("999999","FG_LOT_NO_ON",conn);
						System.out.println("ls_fglotnoon..."+ls_fglotnoon);
                        if (ls_fglotnoon.equalsIgnoreCase("R"))
						 {
							if("RFP".indexOf(ordertypeT)>-1)
								 {
								     if(genlotnoT.equalsIgnoreCase("1") || (lb_nositeitem && ls_setfg.trim().indexOf(sitecode.trim()) > -1 ))
										  {	     
										          if(lotno == null || lotno.trim().length() == 0)  
											       {    
														tranIdG = generateTranId(ls_win,getCurrdateAppFormat(),lotno,sitecode,itemcode,conn);
														System.out.println("tranIdG.........."+tranIdG);
														if(tranIdG.equalsIgnoreCase("ERROR") || tranIdG.trim().length() == 0)
													     {
															 errCode = "NOLOTNO";
							                                 errString = getErrorString("",errCode,userId);
													     }
														System.out.println("workorder.........."+workorder);
														sqlUpd = " update workorder_receipt set lot_no ='"+tranIdG+"' where work_order = '"+workorder+"'";
														updCnt = stmt.executeUpdate(sqlUpd);
														if (updCnt == 1)
															{
																System.out.println("Update Into workorder Successfully....:: " + updCnt);
																conn.commit();
															}
														else if (updCnt == 0)
															{
																System.out.println("No Updation Occur Into workorder ....:: " + updCnt);
																conn.rollback();
																errCode = "NOWORKODRNO";
							                                    errString = getErrorString("",errCode,userId);
															}
														
														
												   }
										  }
							

						         }

					     }
				   
					}  	
			    	stmt.close();
			    	stmt = null;	
			}
		}
	
		
		catch(Exception e)
		{
			System.out.println("The Exception occurs in WORPostSaveEJB........ :"+e);	
			try
			{
				conn.rollback();
			}
			catch (Exception e1){}
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs !=null)
				{
					rs.close();
			        rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				
				
			} 
			catch(Exception e)
			{
				System.err.println("Exception :WORPostSaveEJB......... :\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		System.out.println("errString...2"+errString);
		return errString;
	}
	
  //Culculate the trantype value from disparm	
  public String getDisparams(String prdCode,String varName,Connection conn)
	{
		String retVal = "";
		String sql = "";
		ResultSet rs = null;
		Statement stmt = null;
		try
		{
			System.out.println("In DISPAREM ");
			stmt = conn.createStatement();
			sql = "SELECT VAR_VALUE FROM DISPARM WHERE PRD_CODE ='"+prdCode+"' AND VAR_NAME ='"+varName+"'";
			rs = stmt.executeQuery(sql);
			if(!rs.next())
			{
				System.out.println("No record found for PRD_CODE ='"+prdCode+"' AND VAR_NAME ='"+varName+"'");
			}
			else
			{
				retVal = rs.getString(1);
				System.out.println("In DISPAREM retVal.... "+retVal);
			}
			rs.close();
			rs = null;
			stmt.close();
		    stmt = null;
		}
		catch(Exception e)
		{
			System.out.println("Exception in ..getDIS....");
			e.printStackTrace();
		}
		return(retVal);
	}//End of disparm

	//Culculate the trantype value from mfgparm	
  private String getmfgparams(String prdCode,String varName,Connection conn)
	  {
				String retVal = "";
				String sql = "";
				ResultSet rs = null;
				Statement stmt = null;
				try
				{
					System.out.println("In MFGPAREM ");
					stmt = conn.createStatement();
					sql = "SELECT VAR_VALUE FROM  MFGPARM WHERE PRD_CODE ='"+prdCode+"' AND VAR_NAME ='"+varName+"'";
					rs = stmt.executeQuery(sql);
					if(!rs.next())
					{
						System.out.println("No record found for PRD_CODE ='"+prdCode+"' AND VAR_NAME ='"+varName+"'");	
					}
					else
					{
						retVal = rs.getString(1);
						System.out.println("In MFGPAREM retVal..."+retVal);
					}
					rs.close();
			        rs = null;
					stmt.close();
				    stmt = null;
				}
				catch(Exception e)
				{
					System.out.println("Exception in ..getMFG....");
					e.printStackTrace();
				}
				return(retVal);
	  }//End of MFGparm

  private String generateTranId(String windowName,String orderDate,String lot_no, String siteCode,String itemcode,Connection conn)
	{
		
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "",sql1 = "";
		String tranId = "";
		String newKeystring = "";
		String srType = "RS";
		String item_ser = "";
		System.out.println("itemcode...... :"+itemcode);
		try
	     {
	    	sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW= '"+windowName+"'";
		
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			System.out.println("keyString :"+rs.toString());
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);				
			}
			rs.close();
			rs = null;
		    System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			try
		         {
	                    sql1 = "SELECT item_ser from item where item_code = '"+itemcode+"'"	;
						System.out.println("sql1 ....:"+sql1);
						rs = stmt.executeQuery(sql1);
						if(rs.next())
						{
							item_ser = rs.getString(1);
							System.out.println("item_ser..."+item_ser);
							
						}
						else
						{
							System.out.println("No record found ");
						}
						rs.close();
			            rs = null;
						
				 }
			
			catch(Exception e)
				 {
						   System.out.println("Exception in ..item_ser....");
						   e.printStackTrace();
						
			     }
		    stmt.close();
		    stmt = null;
			String xmlValues = "";
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +	"<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues + "<tran_date>"+ orderDate + "</tran_date>";
			xmlValues = xmlValues + "<item_ser>"+ item_ser + "</item_ser>";
			xmlValues = xmlValues + "<item_code>"+itemcode + "</item_code>";
			xmlValues = xmlValues + "<lot_no>" + lot_no + "</lot_no>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
		 }
		 catch (SQLException ex)
		 {
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			
		 }
		 catch (Exception e)
		 {
			System.out.println("Exception ::" + e.getMessage() + ":");
		    e.printStackTrace();
		 }
		return tranId;
	}//generateTranTd()

  private Node getCurrentDetailFromDom(Document dom,String domId)
	{
		NodeList detailList = null;
		Node currDetail = null,reqDetail = null;
		String currDomId = "";
		int	detailListLength = 0;
        detailList = dom.getElementsByTagName("Detail1");
		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;
	}
	//THIS FUNCTION RETURN DATE IN APPLICATION FORMAT	
  private String getCurrdateAppFormat()
		{
			String currAppdate = "";
			java.sql.Timestamp currDate = null;
			try
			{
				    GenericUtility genericUtility = GenericUtility.getInstance();
					Object date = null;
					currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
					System.out.println(genericUtility.getDBDateFormat());
					SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
					date = sdf.parse(currDate.toString());
					currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
					currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
			}
			catch(Exception e)
			{
				    System.out.println("Exception in :::currdate"+e.getMessage());
			}
			return (currAppdate);
		}
	
}
