package ibase.webitm.ejb.eou;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.*;
import java.sql.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import ibase.system.config.AppConnectParm;
import ibase.webitm.utility.ITMException;
import org.w3c.dom.*;
//import ibase.webitm.ejb.MasterStateful;
//import ibase.webitm.ejb.MasterStatefulHome;

@Stateless //added for ejb3

//public class ConfirmLopAmdEJB extends ActionHandlerEJB implements SessionBean
public class ConfirmLopAmd extends ActionHandlerEJB implements ConfirmLopAmdLocal, ConfirmLopAmdRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	String errorString = null;
	/*
	public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("Create Method Called....");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}
	*/
	public String actionHandler() throws RemoteException,ITMException
	{
		System.out.println("actionHandler() Method Called....");
		return "";
	}
	public String actionHandler(String xmlString, String xtraParams, String objContext) throws RemoteException,ITMException
	{
		String  retString = null;
		System.out.println("Xtra Params : " + xtraParams);
		//genericUtility = GenericUtility.getInstance();
		try
		{
			retString = actionConfirm(xmlString, xtraParams);
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :actionHandler(String xmlString):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning from  actionHandler"+retString);
	    return (retString);
	}
	private String actionConfirm(String tranID, String xtraParams) throws RemoteException,ITMException, Exception
	{
		Connection conn = null;
		PreparedStatement pstmt = null;
		PreparedStatement Dtlpstmt = null;
		ResultSet rs = null;
		ResultSet Dtlrs = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		String userId ="",loginSite ="",empCode="";
		userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
		empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
		System.out.println("empCode.......... !"+empCode);
		String sql = "";
        String retString = "";
		int count =0,i=0,upd=0;
		System.out.println("tranID ...."+tranID );
		ArrayList arrayList =new ArrayList();
		ArrayList itemList =new ArrayList();
		ArrayList arrayListItem =new ArrayList();
		HashMap hm =new HashMap();
		HashMap currentMap =new HashMap();
		HashMap itemLiscontracmap =new HashMap();
		String lsConf = "Y";
		String  itemCode ="",siteCode ="",unit ="",phyAttrib1="",phyAttrib2 ="",phyAttrib3 ="",phyAttrib4 ="",phyAttrib5 ="",phyAttrib6 ="";
		String suppSour="",itemCodenew="",returnString="",item_type="",item_ser="";
		String contract="",errorCode ="";
		HashMap stkUpdMap = null;
		double quantity = 0.0;
		double qtyTotal = 0;
		Timestamp validUptoTs = null,validFromTs = null;
		double qtySamDbSum = 0.0;
		Timestamp tranDate = null;
		String itemDescr = "",buySellFlag ="",itemStatus = "",tariffHead = "";
		String itemCodeOld = "",itemDescrOld = "",buySellFlagOld = "",itemStatusOld = "",tariffHeadOld = "";
		int lineNoLop = 0;
		double ConvQty = 0, finalTot = 0,ConvQtyTot = 0;
		String qty = "",authLoc = "",lineNo = "",lopRefNo= "",lotNo = "",qtySample = "",convQty = "",unitStd = "",qtyStd = "",remarks = "";
		String errString = "",qorderNo = "",confirmed = "";
		String authLocOld = "";
		Timestamp validFromTsOld = null,validUptoTsOld = null;
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			Timestamp currDate = null;
			String currAppdate = null;
			int maxLineNo = 0,incr = 0;
			currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println("\n today date----" + currDate);
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
			System.out.println("\n today currDate in apl----" + currAppdate);
			currAppdate = genericUtility.getValidDateString(currAppdate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
			System.out.println("\n today currDate in DB----" + currAppdate);
			currDate = Timestamp.valueOf(currAppdate + " 00:00:00.00");
			System.out.println("\n today currDate in timestamp----" + currDate);
			sql = " select auth_loc,valid_from,valid_to,lop_ref_no,confirmed "
					+ " from lop_amd_hdr"
					+ " where tran_id = '" + tranID+"'";
			pstmt= conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			 {
				authLoc = rs.getString("auth_loc") == null ? "" : rs.getString("auth_loc");
				validFromTs = rs.getTimestamp("valid_from");
				validUptoTs = rs.getTimestamp("valid_to");
				lopRefNo = rs.getString("lop_ref_no") == null ? "" : rs.getString("lop_ref_no");
				confirmed = rs.getString("confirmed");
			 }
			pstmt.close();
			rs.close();
			pstmt = null;
			rs = null;
			sql = "select auth_loc,valid_from,valid_to "
								+ " from lop_hdr"
								+ " where lop_ref_no = '" + lopRefNo + "'";
			pstmt= conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			 {
				authLocOld = rs.getString("auth_loc") == null ? "" : rs.getString("auth_loc");
				validFromTsOld = rs.getTimestamp("valid_from");
				validUptoTsOld = rs.getTimestamp("valid_to");
			 }
			pstmt.close();
			rs.close();
			pstmt = null;
			rs = null;
			if(confirmed == null || !confirmed.equalsIgnoreCase("Y") )
			{
				sql = " update lop_amd_hdr "
						+ " set   confirmed  = 'Y',"
						+ " conf_date = ? ,"
						+ " emp_code__aprv =?"
						+ " where tran_id = ?";
				System.out.println("\n sql for update----" + sql);
				pstmt = conn.prepareStatement(sql);
				pstmt.setTimestamp(1, currDate);
				pstmt.setString(2, userId);
				pstmt.setString(3, tranID);
				pstmt.executeUpdate();
				pstmt.close();
				pstmt = null;
				sql = " update lop_hdr "
						+ " set  auth_loc =?,"
						+ " valid_from = ? ,"
						+ " valid_to = ? "
						+ " where lop_ref_no = '" + lopRefNo + "'";
				System.out.println("\n sql for update----" + sql);
				pstmt = conn.prepareStatement(sql);
				if(authLoc != null && authLoc.trim().length() > 0)
				{
					pstmt.setString(1, authLoc);
				}
				else
				{
					pstmt.setString(1, authLocOld);
				}
				if(validFromTs != null )
				{
					pstmt.setTimestamp(2, validFromTs);
				}
				else
				{
					pstmt.setTimestamp(2, validFromTsOld);
				}
				if(validFromTs != null )
				{
					pstmt.setTimestamp(3, validUptoTs);
				}
				else
				{
					pstmt.setTimestamp(3, validUptoTsOld);
				}
				pstmt.executeUpdate();
				pstmt.close();
				pstmt = null;
				sql = " select item_code,item_descr,buy_sell_flag,"
							+ " item_status,tariff_head ,line_no_lop"
							+ "  from lop_amd_det"
							+ " where tran_id = '" + tranID +"'";
				pstmt= conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				while(rs.next())
				 {
				   itemCode = rs.getString("item_code") == null ? "" : rs.getString("item_code");
				   itemDescr = rs.getString("item_descr") == null ? "" : rs.getString("item_descr");
				   buySellFlag = rs.getString("buy_sell_flag") == null ? "" : rs.getString("buy_sell_flag");
				   itemStatus = rs.getString("item_status") == null ? "" : rs.getString("item_status");
				   tariffHead = rs.getString("tariff_head") == null ? "" : rs.getString("tariff_head");
				   lineNoLop = rs.getInt("line_no_lop") ;
				   System.out.println("lineNoLop >>>>>>>>>>>>>> " + lineNoLop);
				   
				   
				   if(lineNoLop == 0)
				   {
						sql = "select max(line_no) from lop_det where lop_ref_no = '" + lopRefNo +"'";
						System.out.println("sql for max line no >>>>>>>>>> " + sql);
						Dtlpstmt = conn.prepareStatement(sql);
						Dtlrs = pstmt.executeQuery();
						if(Dtlrs.next() )
						{
							maxLineNo = rs.getInt(1);
						}
						Dtlrs.close();
						Dtlrs = null;
						Dtlpstmt.close();
						Dtlpstmt = null;
						System.out.println("max line for this tran id " + lopRefNo + " = " + maxLineNo);
						sql = " insert into lop_det" 
								+ " (lop_ref_no,line_no,item_code,"
								+ " item_descr,buy_sell_flag,item_status,tariff_head  )"
								+ " values( ?,?,?,"
								+ " ?,?,?,?)";
						Dtlpstmt = conn.prepareStatement(sql);
						Dtlpstmt.setString(1,lopRefNo);
						Dtlpstmt.setInt(2,maxLineNo + 1);
						Dtlpstmt.setString(3,itemCode);
						Dtlpstmt.setString(4,itemDescr);
						Dtlpstmt.setString(5,buySellFlag);
						Dtlpstmt.setString(6,itemStatus);
						Dtlpstmt.setString(7,tariffHead);
						Dtlpstmt.executeUpdate();
						Dtlpstmt.close();
						Dtlpstmt = null;
						maxLineNo = 0;
				   }
				   else
				   {
						sql = " select item_code,item_descr,buy_sell_flag,item_status,tariff_head "
								+ " from lop_det"
								+ " where lop_ref_no = '" + lopRefNo + "'"
								+ " and line_no = '" + lineNoLop + "'";
						Dtlpstmt= conn.prepareStatement(sql);
						Dtlrs = Dtlpstmt.executeQuery();
						if(Dtlrs.next())
						 {
						   itemCodeOld = Dtlrs.getString("item_code") == null ? "" : Dtlrs.getString("item_code");
						   itemDescrOld = Dtlrs.getString("item_descr") == null ? "" : Dtlrs.getString("item_descr");
						   buySellFlagOld = Dtlrs.getString("buy_sell_flag") == null ? "" : Dtlrs.getString("buy_sell_flag");
						   itemStatusOld = Dtlrs.getString("item_status") == null ? "" : Dtlrs.getString("item_status");
						   tariffHeadOld = Dtlrs.getString("tariff_head") == null ? "" : Dtlrs.getString("tariff_head");
						 }
						Dtlpstmt.close();
						Dtlrs.close();
						Dtlpstmt = null;
						Dtlrs = null;
						sql = " update lop_det "
									+ " set item_code = ?,"
									+ " item_descr = ?,"
									+ " buy_sell_flag = ?,"
									+ " item_status = ?,"
									+ " tariff_head = ? "
									+ " where lop_ref_no = '" + lopRefNo + "'"
									+ " and line_no = " + lineNoLop;
						Dtlpstmt = conn.prepareStatement(sql);
						if(itemCode != null && itemCode.trim().length() > 0)
						{
							Dtlpstmt.setString(1,itemCode);
						}
						else
						{
							Dtlpstmt.setString(1,itemCodeOld);
						}
						if(itemCode != null && itemCode.trim().length() > 0)
						{
							Dtlpstmt.setString(2,itemDescr);
						}
						else
						{
							Dtlpstmt.setString(2,itemDescrOld);
						}
						if(itemCode != null && itemCode.trim().length() > 0)
						{
							Dtlpstmt.setString(3,buySellFlag);
						}
						else
						{
							Dtlpstmt.setString(3,buySellFlagOld);
						}
						if(itemCode != null && itemCode.trim().length() > 0)
						{
							Dtlpstmt.setString(4,itemStatus);
						}
						else
						{
							Dtlpstmt.setString(4,itemStatusOld);
						}
						if(itemCode != null && itemCode.trim().length() > 0)
						{
							Dtlpstmt.setString(5,tariffHead);
						}
						else
						{
							Dtlpstmt.setString(5,tariffHeadOld);
						}
						Dtlpstmt.executeUpdate();
						Dtlpstmt.close();
						Dtlpstmt = null;
				   }
				 }
				pstmt.close();
				rs.close();
				pstmt = null;
				rs = null;
				errString = itmDBAccessEJB.getErrorString("","CONLASUCC","BASE");
			}
			else
			{
				errString = itmDBAccessEJB.getErrorString("","VTRCONF1","BASE");
			}
		}
		catch(Exception e)
		{
			System.out.println("ConfirmLopEJB..."+e.getMessage());
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
			   System.out.println("ConfirmLopEJB..."+e1.getMessage());
			   e1.printStackTrace();
			}
		}
		finally
		{
			try
			{
				conn.commit();
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
				if(Dtlrs != null )Dtlrs.close();
				Dtlrs = null;
				if(Dtlpstmt != null) Dtlpstmt.close();
				Dtlpstmt = null;
			}
			catch(Exception e)
			{
				System.out.println("Exception ConfirmLopEJB....... :\n"+e.getMessage());
			}
		}
		System.out.println("retString ::" + errString);
		return errString ;
	}// end actConfirm
}
