/**
 * Author : Chaitali Parab
 * Date   : 
 * 
 * */

package ibase.webitm.ejb.wms;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.text.SimpleDateFormat;
import org.w3c.dom.*;

import ibase.system.config.*;
import ibase.webitm.ejb.*; 

import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.dis.*;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;

@javax.ejb.Stateless
public class AsnLotStatConf extends ValidatorEJB implements AsnLotStatConfLocal, AsnLotStatConfRemote
{

	public String postSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String postSave( String domString, String tranId,String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		String errMsg = "";
		String tranIdRel = "";
		String lineNoRel = "";
		String itemCode = "";
		String lotNo = "";
		String sql = "";
		String invHoldRelSql = "";
		String invHoldRelDetSql = "";
		String siteCode = "";
		String confirmed = "";
		String empCode = "";
		String remark = "";
		String itemCodeDet = "";
		String lotNoDet = "";
		String lineNo = "";
		String tranIdGenerate = "";

		boolean flag = false;

		int count = 0;
		int updCnt = 0;
		int ctr = 0;
		int lineNoCtr = 0;
		java.sql.Timestamp chgDate = null,currDate = null;
		Date date = null;
		String chgTerm = "";
		String userId = "";
		String lotStatus = "";
		String lockCode = "";
		Document dom = null;

		PreparedStatement pStmt = null;
		PreparedStatement pRelHdr = null;
		PreparedStatement pRelDet = null;
		ResultSet rs = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessLocal = new ITMDBAccessEJB();

		HashMap tempMap = null;
		try
		{
			dom = genericUtility.parseString(domString);

			invHoldRelSql = "INSERT INTO INV_HOLD_REL(TRAN_ID, TRAN_DATE, SITE_CODE, REMARKS, CONFIRMED, EMP_CODE__APRV,CHG_USER ,CHG_DATE, CHG_TERM) VALUES(?,?,?,?,?,?,?,?,?)";
			pRelHdr = conn.prepareStatement(invHoldRelSql);
			invHoldRelDetSql = "INSERT INTO INV_HOLD_REL_DET(TRAN_ID, LINE_NO, TRAN_ID__HOLD, LINE_NO__HOLD, REMARKS) VALUES(?,?,?,?,?)";
			pRelDet = conn.prepareStatement(invHoldRelDetSql);

			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );
			siteCode =  GenericUtility.getInstance().getColumnValueFromNode("site_code", dom.getElementsByTagName("Detail1").item(0));
			confirmed = "N";
			empCode = "";

			SimpleDateFormat sdfAppl = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String currDateStr = sdfAppl.format(currDate);

			tranIdGenerate = generateTranId( "w_inv_hold_rel", siteCode, currDateStr, conn );

			pRelHdr.setString( 1, tranIdGenerate );
			pRelHdr.setTimestamp( 2, currDate );
			pRelHdr.setString( 3, siteCode );
			pRelHdr.setString( 4, " " );
			pRelHdr.setString( 5, confirmed );
			pRelHdr.setString( 6, empCode );
			pRelHdr.setString( 7, userId );
			pRelHdr.setTimestamp( 8, currDate );
			pRelHdr.setString( 9, chgTerm );

			updCnt = pRelHdr.executeUpdate();
			pRelHdr.clearParameters();
			if( updCnt > 0 )
			{					
				System.out.println( updCnt + " rows updated successfully" );
			}

			int length = dom.getElementsByTagName( "Detail2").getLength();
			for ( int pctr = 0; pctr < length; pctr++ )
			{
				lotStatus = GenericUtility.getInstance().getColumnValueFromNode("lot_status", dom.getElementsByTagName("Detail2").item(pctr));
				if(lotStatus.equalsIgnoreCase("A"))
				{
					lineNo = GenericUtility.getInstance().getColumnValueFromNode("line_no", dom.getElementsByTagName("Detail2").item(pctr));
					itemCodeDet = GenericUtility.getInstance().getColumnValueFromNode("item_code", dom.getElementsByTagName("Detail2").item(pctr));
					lotNoDet = GenericUtility.getInstance().getColumnValueFromNode("lot_no", dom.getElementsByTagName("Detail2").item(pctr));
					lockCode = GenericUtility.getInstance().getColumnValueFromNode("lock_code", dom.getElementsByTagName("Detail2").item(pctr));
					sql = "select count(*) from asn_det where item_code = ? and lot_no = ?";
					pStmt = conn.prepareStatement(sql);
					pStmt.setString(1, itemCodeDet);
					pStmt.setString(2, lotNoDet);
					rs = pStmt.executeQuery();
					if( rs.next() )
					{
						count = rs.getInt(1);
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;					

					if(count != 0)
					{
						ctr++;
						//flag = true;
						sql = "select ih.tran_id, ih.line_no from inv_hold h, inv_hold_det ih"
							+" where h.tran_id = ih.tran_id"
							+" and h.ref_id in ("
							+" select p.tran_id from porcp p where p.asn_no in ("
							+" select ah.asn_no from asn_hdr ah where ah.tran_id in ("
							+" select tran_id from asn_det ad where ad.item_code = ? and ad.lot_no = ? )"
							+" ) ) and h.lock_code = ?"
							+" and ih.item_code = ?"
							+" and ih.lot_no = ?"
							+" and ih.hold_status = 'H'";
						pStmt = conn.prepareStatement(sql);
						pStmt.setString(1, itemCodeDet);
						pStmt.setString(2, lotNoDet);
						pStmt.setString(3, lockCode);
						pStmt.setString(4, itemCodeDet);
						pStmt.setString(5, lotNoDet);
						rs = pStmt.executeQuery();
						
						if( rs.next() )
						{
							lineNoCtr++;
							tranIdRel = rs.getString("tran_id");
							lineNoRel = rs.getString("line_no");
							pRelDet.setString( 1, tranIdGenerate );
							pRelDet.setInt( 2,lineNoCtr);
							pRelDet.setString( 3, tranIdRel );
							pRelDet.setString( 4, lineNoRel );
							pRelDet.setString( 5, remark );
							pRelDet.addBatch();
							pRelDet.clearParameters();
					
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;					

					
						//updCnt = pRelDet.executeUpdate();
						
						if( updCnt > 0 )
						{					
							System.out.println( updCnt + " rows updated successfully" );
						}
					}								
				}//lotStatus = 'A'
			}//for pctr

			pRelDet.executeBatch();
			pRelDet.clearBatch();
			//if(flag == true)
			if(length == ctr)
			{
				sql = "update asn_lot_stat set confirmed = 'Y', conf_date = ? where tran_id = ?";
				pStmt = conn.prepareStatement(sql);
				pStmt.setTimestamp(1,currDate);
				pStmt.setString(2,tranId);
				int rowcnt = pStmt.executeUpdate();
				if(rowcnt == 0)
				{
					errMsg = itmDBAccessLocal.getErrorString("","VTMCONF9","");
					return errMsg;
				}
				else
				{
					//errMsg = itmDBAccessLocal.getErrorString("","VTMCONF2","");
					//return errMsg;
				}
			}

		}
		catch(BatchUpdateException buex)
        {
			try
			{
				conn.rollback();
				int [] updateCounts = buex.getUpdateCounts();
				for (int i = 0; i < updateCounts.length; i++)
				{
					System.err.println("  Statement " + i + ":" + updateCounts[i]);
				}
				System.err.println(" Message: " + buex.getMessage());
				System.err.println(" SQLSTATE: " + buex.getSQLState());
				System.err.println(" Error code: " + buex.getErrorCode());
				SQLException ex = buex.getNextException();
				while (ex != null)
				{ 
					System.err.println("SQL exception:");
					System.err.println(" Message: " + ex.getMessage());
					System.err.println(" SQLSTATE: " + ex.getSQLState());
					System.err.println(" Error code: " + ex.getErrorCode());
					ex = ex.getNextException();
				}
			}
			catch ( Exception e)
			{
				e.printStackTrace();
			}
			throw new ITMException(buex);
        }
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(pRelDet != null)
				{
					pRelDet.close();
					pRelDet = null;
				}
				if(pRelHdr != null)
				{
					pRelHdr.close();
					pRelHdr = null;
				}
				if(pStmt != null)
				{
					pStmt.close();
					pStmt = null;
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return errMsg;
	}	
	private String checkNull( String input )
	{
		if ( input == null )
		{
			input = "";
		}
		return input;
	}
	private String generateTranId( String windowName, String siteCode, String tranDateStr, Connection conn )throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selSql = "";
		String tranId = "";
		String tranSer = "";
		String keyString = "";
		String keyCol = "";
		String xmlValues = "";
		String paySiteCode = "";
		String effectiveDate = "";

		java.sql.Date effDate = null;

		try
		{
			selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			//System.out.println("selSql :"+selSql);
			pstmt = conn.prepareStatement(selSql);
			pstmt.setString( 1, windowName );
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				keyString = rs.getString("KEY_STRING");
				keyCol = rs.getString("TRAN_ID_COL");
				tranSer = rs.getString("REF_SER");
			}
			rs.close();rs = null;
			pstmt.close();pstmt = null;
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer :"+tranSer);

			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>" + tranDateStr + "</tran_date>"; 
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);

		}
		catch (SQLException ex)
		{
			System.out.println("Exception ::" +selSql+ ex.getMessage() + ":");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		catch (Exception e)
		{
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{

			}
		}
		return tranId;
	}//generateTranTd()		
}