/**
	* @author : Chandni Shah 
	* @Version : 1.0
	* Date :04/10/10
*/
package ibase.webitm.ejb.mfg.adv;
 
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.ejb.CreateException;
//import javax.ejb.SessionBean;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
 
public class QcOrderAct extends ActionHandlerEJB implements  QcOrderActLocal , QcOrderActRemote //SessionBean
{
	/**
	 * 
	 */
	
	/*public void ejbCreate() throws RemoteException, CreateException {
	}

	public void ejbRemove() {
	}

	public void ejbActivate() {
	}

	public void ejbPassivate() {
	}*/

	public String actionHandler() throws RemoteException, ITMException 
	{
		return "";
	}
	
	/**
	
	* @param actionType    identifier for action
	* @param xmlString     current form data
	* @param xmlString1    header data in XML form
	* @param objContext    form number of current form
	* @param xtraParams    logged in user information
	* @return retString    method returns the XML String
	* @see genericUtility  
	* @see #actionStock     Getting Value for Stock
	*/
	public String actionHandler(String actionType, String xmlString,
			String xmlString1, String objContext, String xtraParams)
			throws RemoteException, ITMException 
	{
		Document dom = null;
		Document dom1 = null;

		String retString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try 
		{
			if (xmlString != null && xmlString.trim().length() != 0) 
			{
				System.out.println("XML String :" + xmlString);
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) 
			{
				System.out.println("XML String1 :" + xmlString1);
				dom1 = genericUtility.parseString(xmlString1);
			}

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

			if (actionType.equalsIgnoreCase("Stock")) 
			{
				retString = actionStock(dom, dom1, xtraParams);
			}
		}
		catch (Exception e) 
		{
			System.out.println("Exception :QcOrderAct :actionHandler(String xmlString):"
							+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from QcOrderAct : actionHandler"
						+ retString);
		return retString;
	}
	/**
	* @param actionType    identifier for action
	* @param xmlString     current form data
	* @param xmlString1    header data in xml form    
	* @param objContext    form number of current form
	* @param xtraParams		logged in user information
	* @param selDataStr	    
	* @return retString    method returns the XML String
	* @see genericUtility  
	*/
	public String actionHandlerTransform(String actionType, String xmlString,
			String xmlString1, String objContext, String xtraParams,
			String selDataStr) throws RemoteException, ITMException
	{
		System.out.println("actionHandlerTransform is calling.............");
		Document dom = null;
		Document dom1 = null;
		Document selDataDom = null;

		String retString = null;
		try
		{
			if (xmlString != null && xmlString.trim().length() != 0) 
			{
				dom = GenericUtility.getInstance().parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) 
			{
				dom1 = GenericUtility.getInstance().parseString(xmlString1);
			}
			if (selDataStr != null && selDataStr.length() > 0) 
			{
				selDataDom = GenericUtility.getInstance().parseString(selDataStr);
			}
			System.out.println("selDataStr:" + selDataStr + ":");
			System.out.println("actionType:" + actionType + ":");

			if (actionType.equalsIgnoreCase("Stock"))
			{
				retString = stockTransform(dom, dom1, objContext, xtraParams,selDataDom);
			}
		}
		catch (Exception e) 
		{
			System.out.println("Exception :QcOrderAct :actionHandlerTransform(String xmlString):"
							+ e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from QcOrderAct : actionHandlerTransform"+ retString);
		return retString;
	}

	/**
	* @param dom               get document object model
	* @param dom1              get document object model1
	* @param xtraParams
	* @return valueXmlString   returns in string buffer
	* @see genericUtility  
	
	*/
	private String actionStock(Document dom, Document dom1, String xtraParams)throws RemoteException, ITMException 
	{
		String siteCode = "", itemCode = "", lotNo = "" ,descr ="", trackShelfLife = "" ;
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Connection conn = null;
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		DistCommon dist = new DistCommon();
		if (dom == null)
		{
			valueXmlString.append("</Root>\r\n");
			return valueXmlString.toString();
		}
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		try 
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			itemCode = genericUtility.getColumnValue("item_code", dom1);
			siteCode = genericUtility.getColumnValue("site_code", dom1);
			lotNo = genericUtility.getColumnValue("lot_no",dom1);
			if (itemCode != null)
			{
				sql = " select descr from item where item_code = ? ";
						
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						descr = rs.getString(1);
					}
					pstmt.close();
					System.out.println("DESCRIPTION IS ==========" + descr);
			}
			// 18/08/14 manoharan hold_qty not to be considered as as each QC will have a corresponding lock also
			sql = " SELECT stock.item_ser,stock.item_code,stock.unit,stock.loc_code,stock.lot_no, stock.lot_sl,   "
				+ " stock.site_code, stock.exp_date, stock.retest_date, stock.pack_code, stock.quantity  - case "
				+" when stock.alloc_qty is null then 0 else stock.alloc_qty end as quantity "
				+" FROM stock,invstat  "
				+" WHERE ( stock.inv_stat = invstat.inv_stat ) and  "
				+" ( stock.item_code = ? ) AND  "
				+" ( stock.site_code = ?) AND  "
				+" ( stock.lot_no = ?) AND  "
				+" ( stock.quantity  - case when stock.alloc_qty is null then 0 else stock.alloc_qty end >  0 )";
				//+" - case when stock.hold_qty is null then 0 else stock.hold_qty end > 0 )  "  ;
			 //"- case when stock.hold_qty is null then 0 else stock.hold_qty end "
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			pstmt.setString(3, lotNo);
			rs = pstmt.executeQuery();
			
			int counter = 0;
			while (rs.next())
			{
				valueXmlString.append("<Detail>\r\n");
				valueXmlString.append("<line_no>").append("<![CDATA[").append(counter).append("]]>").append("</line_no>\r\n");			
				valueXmlString.append("<item_ser>").append("<![CDATA[").append(rs.getString(1)).append("]]>").append("</item_ser>\r\n");			
				valueXmlString.append("<item_code>").append("<![CDATA[").append(rs.getString(2)).append("]]>").append("</item_code>\r\n");			
				valueXmlString.append("<descr>").append("<![CDATA[").append(descr).append("]]>").append("</descr>\r\n");
				valueXmlString.append("<unit>").append("<![CDATA[").append(rs.getString(3)).append("]]>").append("</unit>\r\n");			
				valueXmlString.append("<loc_code>").append("<![CDATA[").append(rs.getString(4)).append("]]>").append("</loc_code>\r\n");			
				valueXmlString.append("<lot_no>").append("<![CDATA[").append(rs.getString(5)).append("]]>").append("</lot_no>\r\n");			
				valueXmlString.append("<lot_sl>").append("<![CDATA[").append(rs.getString(6)).append("]]>").append("</lot_sl>\r\n");
				valueXmlString.append("<site_code>").append("<![CDATA[").append(rs.getString(7)).append("]]>").append("</site_code>\r\n");							
				valueXmlString.append("<exp_date>").append("<![CDATA[").append(rs.getString(8)).append("]]>").append("</exp_date>\r\n");
				//valueXmlString.append("<retest_date>").append("<![CDATA[").append(rs.getString(9).trim()).append("]]>").append("</retest_date>\r\n");
				//valueXmlString.append("<pack_code>").append("<![CDATA[").append(rs.getString(10).trim()).append("]]>").append("</pack_code>\r\n");
				valueXmlString.append("<quantity>").append("<![CDATA[").append(rs.getDouble(11)).append("]]>").append("</quantity>\r\n");
				valueXmlString.append("</Detail>");	
				//valueXmlString.append("</ >\r\n");
				counter++;
			}
			rs.close();
			pstmt.close();
			valueXmlString.append("</Root>\r\n");
		}//try end
		catch (SQLException sqx)
		{
			System.out.println("The SQLException occurs in QcOrderAct for Stock button :" + sqx);
			sqx.printStackTrace();
			throw new ITMException(sqx);
        }
		catch (Exception e)
		{
			System.out.println("The Exception occure in QcOrderAct  for Stock button:" + e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				conn.close();
				conn = null;
			} 
			catch (Exception e)
			{
			}
		}
		System.out.println("valueXmlString return from actionStock :"	+ valueXmlString.toString());
		return valueXmlString.toString();
	}

	/*
	@param dom    
	@param dom1   
	@param objContext    form number of current form
	@param xtraParams    logged in user information
	@param selDataDom     logged in user information
	@return valueXmlString    method returns the XML String
	@see genericUtility  
	*/
	private String stockTransform(Document dom, Document dom1, String objContext, String xtraParams, Document selDataDom) throws ITMException 
	{
		System.out.println("stockTransform is calling.............");
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		String sql = null, errCode = "", errString = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String selectedrow = "";
		String quantity = "", qtyPassed = "", qtyRej = "", qtySample = "", qty = "";
		String qcOrder ="", itemCode ="", lotNo ="", lotSl ="",locCode ="", unit ="" ,itemDescr = "";
		String locType="",locLogic ="",site ="",locUdf ="",loc ="",trackShelfLife = "N";
		int count = 0 , line = 0;
		Node currDetail1 = null;
		DistCommon dist = new DistCommon();
		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try 
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			NodeList detailList = selDataDom.getElementsByTagName("Detail");
			locLogic = dist.getDisparams ("999999","APR_LOC_LOGIC",conn);
			locUdf  = dist.getDisparams ("999999","APR_LOC_UDF",conn);
			System.out.println ("locLogic is = ===== "+locLogic);
			System.out.println ("locUdf is = ===== "+locUdf);
			selectedrow = genericUtility.getColumnValue("selectedrow",selDataDom);
			qty   = genericUtility.getColumnValue("quantity",dom1);
			int noOfDetails = detailList.getLength();
			if (qty == null) 
			{
				qty = "0";
			}
			qtyPassed =  genericUtility.getColumnValue("qty_passed",dom1);
			if (qtyPassed == null )
			{
				qtyPassed = "0";
			}
			qtyRej	 = genericUtility.getColumnValue("qty_rejected",dom1);
			if (qtyRej == null)
			{
				qtyRej = "0";
			}
			itemCode		  = genericUtility.getColumnValue("item_code", selDataDom);
			itemDescr = 	 genericUtility.getColumnValue("descr", selDataDom);
			qtySample = genericUtility.getColumnValue("qty_sample", dom1);

			sql = " select track_shelf_life from item "
				+" where item_code = ? " ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				trackShelfLife = rs.getString(1);
			}
			pstmt.close();
			if (trackShelfLife == null)
			{
				trackShelfLife = "N";
			}


			if (qtySample == null)
			{
				qtySample = "0";
			}
			site =genericUtility.getColumnValue("site_code", dom1);
			if (((Double.parseDouble(qtySample)) + (Double.parseDouble(qtyRej))) == (Double.parseDouble(qty)))
			{
				locCode = genericUtility.getColumnValue("loc_code__rej", dom1);
				locType = "R";
			}
			else
			{
				locCode =genericUtility.getColumnValue("loc_code__aprv", dom1);
				locType = "A";
			}
			if (locCode ==  null  &&  ("A".equalsIgnoreCase (locType )))
			{
				if (locLogic.equalsIgnoreCase("NULLFOUND"))
				{
					errCode = "VTLOCLOG"; 
					errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
					conn.close();
					conn = null;
					return errString;
				}
				if ("U".equalsIgnoreCase (locLogic ))
				{	
					if (locUdf.equalsIgnoreCase("NULLFOUND")|| locUdf.trim().length() == 0)
					{
						System.out.println("inside if locUdf *********");
						errCode = "VTLOCUDF"; 
						errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
						conn.close();
						conn = null;
						return errString;
					}
				}
				if ("I".equalsIgnoreCase (locLogic ))
				{
					sql = " select LOC_CODE from itemCode "
						+" where item_code = ? " ;
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						locCode = rs.getString(1);
					}
					pstmt.close();
				}
				else if ("S".equalsIgnoreCase(locLogic))
				{
					sql = "select LOC_CODE__APRV from siteitem "
						+" where item_code = ? and site_code = ? " ;
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					pstmt.setString(2, site);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						locCode = rs.getString(1);
					}
					pstmt.close();
				}		
			}
			if (noOfDetails > 0) 
			{
				sql = " select case when max(line_no) + 1 is null then 1 else max(line_no) + 1 end   "
					+"  from	qc_order_lots "
					+" where	qc_order  = ?"
					+" and	item_code = ?		"
					+" and	lot_no	 = ? " ;
					
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, qcOrder );
					pstmt.setString(2, itemCode);
					pstmt.setString(3, lotNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						line = rs.getInt(1);
					}
					pstmt.close();
					rs.close();
				for (int ctr = 0; ctr < noOfDetails ; ctr++) 
				{
					valueXmlString.append("<Detail>\r\n");
					currDetail1 = detailList.item(ctr);
					qcOrder	  = genericUtility.getColumnValue("qorder_no", dom1);
					itemCode  = genericUtility.getColumnValueFromNode("item_code", currDetail1);
					//itemDescr = genericUtility.getColumnValueFromNode("descr", currDetail1);
					lotNo	  = genericUtility.getColumnValueFromNode("lot_no", currDetail1);
					lotSl	  = genericUtility.getColumnValueFromNode("lot_sl", currDetail1);
					loc	      = genericUtility.getColumnValueFromNode("loc_code", currDetail1);
					quantity  = genericUtility.getColumnValueFromNode("quantity", currDetail1);
					unit		  = genericUtility.getColumnValueFromNode("unit", currDetail1);
					sql = " select	count(1) from	qc_order_lots"
						+" 	where	qc_order  = ? and	item_code = ? "
						+" and lot_no	 = ?		and"
						+" lot_sl	 = ?	and "
						+" loc_code	 = ? " ; 
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, qcOrder);
					pstmt.setString(2, itemCode);
					pstmt.setString(3, lotNo);
					pstmt.setString(4, lotSl);
					pstmt.setString(5, loc);
					rs = pstmt.executeQuery();
					pstmt.close();
					if ( count > 0 )
					{
						errCode = "VTDUPQCLOT"; 
						errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
						conn.close();
						conn = null;
						return errString;
					}
					if ("U".equalsIgnoreCase(locLogic) && locType != "R" )
					{
						if (!(locUdf.equalsIgnoreCase("NULLFOUND")|| locUdf.trim().length() == 0))
						{
							System.out.println("inside 2nd if locUdf *********");
							sql = "select " + locUdf + "('" + loc + "') from dual";
							pstmt = conn.prepareStatement(sql);
							//loc = rs.getString(1);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								locCode = rs.getString(1);
							}
							else
							{
								errCode = "DS000"; 
								errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
								conn.close();
								conn = null;
								return errString;
							}
							pstmt.close();
						}
						else
						{
							errCode = "VTLOCUDF"; 
							errString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
							conn.close();
							conn = null;
							return errString;
						}
					}
					
					valueXmlString.append("<qorder_no isSrvCallOnChg='0'>").append("<![CDATA[").append(qcOrder).append("]]>").append("</qorder_no>\r\n");
					valueXmlString.append("<line_no isSrvCallOnChg='0'>").append("<![CDATA[").append(line).append("]]>").append("</line_no>\r\n");
					valueXmlString.append("<item_code isSrvCallOnChg='0'>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>\r\n");
					valueXmlString.append("<item_descr isSrvCallOnChg='0'>").append("<![CDATA[").append(itemDescr).append("]]>").append("</item_descr>\r\n");
					valueXmlString.append("<lot_no isSrvCallOnChg='0'>").append("<![CDATA[").append(lotNo).append("]]>").append("</lot_no>\r\n");
					valueXmlString.append("<lot_sl isSrvCallOnChg='0'>").append("<![CDATA[").append(lotSl).append("]]>").append("</lot_sl>\r\n");
					valueXmlString.append("<loc_code isSrvCallOnChg='0'>").append("<![CDATA[").append(locCode).append("]]>").append("</loc_code>\r\n");
					valueXmlString.append("<unit isSrvCallOnChg='0'>").append("<![CDATA[").append(unit).append("]]>").append("</unit>\r\n");
					valueXmlString.append("<quantity isSrvCallOnChg='0'>").append("<![CDATA[").append(quantity).append("]]>").append("</quantity>\r\n");
					valueXmlString.append("<loctype isSrvCallOnChg='0'>").append("<![CDATA[").append(locType).append("]]>").append("</loctype>\r\n");
					valueXmlString.append("<loc_code__issue isSrvCallOnChg='0'>").append("<![CDATA[").append(loc).append("]]>").append("</loc_code__issue>\r\n");
					//17-01-11 - chandni shah
					valueXmlString.append("<cc_stkloc isSrvCallOnChg='0'>").append("<![CDATA[").append(loc).append("]]>").append("</cc_stkloc>\r\n");
					valueXmlString.append("<cc_stkqty isSrvCallOnChg='0'>").append("<![CDATA[").append(quantity).append("]]>").append("</cc_stkqty>\r\n");
					valueXmlString.append("</Detail>");	
					line++;
				}// for end
				valueXmlString.append("</Root>");
			}// end if
		}// end try
		catch (ITMException itme)
		{
			itme.printStackTrace();
			throw itme;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection...");
				conn.close();
				conn = null;
			} 
			catch (Exception e)
			{
			}
		}
		System.out.println("valueXmlString from :" + valueXmlString.toString());
		return valueXmlString.toString();
	}
private String updateMessage(String resultString,String message)
    {
        StringBuffer stbf = new StringBuffer();
        try
		{
            System.out.println("resultString : "+resultString);
            stbf.append(resultString.substring(0,resultString.indexOf("<trace>")));
            if(message != null && message.trim().length() > 0)
			{
                stbf.append("<trace>"+message+"</trace>");
                stbf.append(resultString.substring(resultString.indexOf("</trace>")+8));
            }
			else
			{
                stbf.append(resultString.substring(resultString.indexOf("<trace>")));
            }
            System.out.println("Resulting String : "+stbf.toString());
            
        }
		catch(Exception e)
		{
            System.out.println("Exception in updateMessage : "+e);
            e.printStackTrace();
        }
     return stbf.toString();   
    }
}