/***
author -Mukesh Upadhayay
date- 22 august 08

***/

package ibase.webitm.ejb.mfg;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.lang.*;
import javax.ejb.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import javax.naming.InitialContext;

import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.ITMException;
//import ibase.webitm.ITMDBAccessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;

import org.xml.sax.InputSource;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class UpdateWIPLoc extends ProcessEJB implements  UpdateWIPLocLocal,  UpdateWIPLocRemote //SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	CommonConstants commonConstants = new CommonConstants();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	Connection conn = null;

	HashMap userRightsMap = null;
	HashMap winNameMap = null;
	HashMap menuNameMap = null;

	String profileId = null;
	String processStr = null;

	/*public void ejbCreate() throws RemoteException, CreateException
	{

	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		try
		{
			System.out.println("xmlString   ["+xmlString+"]");
			System.out.println("xmlString2   ["+xmlString2+"]");
			System.out.println("windowName   ["+windowName+"]");
			System.out.println("xtraParams   ["+xtraParams+"]");

			if(xmlString != null && xmlString.trim().length()!=0 )
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :UserRightsEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		return rtrStr;
	}


	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{

		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
		String userId = null;
		Object date = null;
		String sql = "";
		String errCode = "";
		String errString = "";
		String resultString = "",workOrder="", sqlStr="";
    	int count = 0;
	    int operation =0,lineNo=0;
	    double quantity =0;
	    String itemCode="", descr="",lotNo="",unit="",
        locCodeWip="",tranId="";

	try
	{
		    userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			workOrder = genericUtility.getColumnValue("work_order", headerDom);

		    if(conn == null)
			{
			     ConnDriver connDriver = new ConnDriver();
				 conn = connDriver.getConnectDB("DriverITM");
				 conn.setAutoCommit(false);
				 connDriver = null;
			}

			sqlStr = " select  a.tran_id,  c.operation,a.Item_Code,b.descr, a.Lot_No,   "+
			"  a.Quantity,a.Unit,a.Loc_Code__wip,a.line_no"+
	        " from workorder_issdet a, item b, workorder_iss c, workorder d    "+
	        "  where a.item_code = b.item_code    "+
	        "  and a.tran_id = c.tran_id     "+
			"  and c.work_order =  d.work_order  "+
	        "  and d.status = 'R'    "+
	        "  and c.work_order = ?    "+
	        "  and not exists (select 1 from workorder_feedback e    "+
	        "  where e.work_order = c.work_order    "+
	        "   and e.operation = c.operation )   ";

			pstmt = conn.prepareStatement(sqlStr);
			System.out.println("The getData sql is:-"+ sqlStr);
			pstmt.setString(1,workOrder);
			rs = pstmt.executeQuery();
	   		while (rs.next())
			{
			
			        tranId= rs.getString(1);
					operation = rs.getInt(2);
					itemCode= rs.getString(3);
					descr =  rs.getString(4);
                    lotNo= rs.getString(5);
					quantity=rs.getDouble(6);
          			unit= rs.getString(7);
					locCodeWip=rs.getString(8);
					lineNo    = rs.getInt(9);


                    System.out.println("\nIn get data >>tranId "+tranId);
					retTabSepStrBuff.append(tranId).append("\t");
					retTabSepStrBuff.append(operation).append("\t");
		    		retTabSepStrBuff.append(itemCode).append("\t");
					retTabSepStrBuff.append(descr).append("\t");
					retTabSepStrBuff.append(lotNo).append("\t");
					retTabSepStrBuff.append(quantity).append("\t");
					retTabSepStrBuff.append(unit).append("\t");
					retTabSepStrBuff.append(locCodeWip).append("\t");
					retTabSepStrBuff.append(lineNo).append("\t");
					retTabSepStrBuff.append(" ").append("\t");
					retTabSepStrBuff.append("\n");


			}//while
	}//try
	catch (SQLException e)
	{
		System.out.println("SQLException ::" + sqlStr + e.getMessage() + ":");
		e.printStackTrace();
	}
	catch(Exception ex)
	{
		System.out.println("Exception []::" + ex.getMessage());
		ex.printStackTrace();
	}
	finally
	{
		try
		{
			    if(rs!=null)
				{
    			    rs.close();
				    rs = null;
                }
                if(pstmt!=null)
				{
				    pstmt.close();
				    pstmt = null;
                }
				if(conn!=null)
				{
			    	conn.close();
				    conn = null;
				}
		}
		catch(Exception e)
		{
			  e.printStackTrace();
		}
	}

		resultString = retTabSepStrBuff.toString();
 		return resultString;
	}//  end of getData()


	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		System.out.println("xmlString2-->"+ xmlString2);
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("xmlString   ["+xmlString+"]");
			System.out.println("xmlString2   ["+xmlString2+"]");
			System.out.println("windowName   ["+windowName+"]");
			System.out.println("xtraParams   ["+xtraParams+"]");
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :UserRightsEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}// end of process
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
			processStr = null;
			GenericUtility genericUtility = GenericUtility.getInstance();
			ConnDriver connDriver = new ConnDriver();
			Connection conn = null;
			PreparedStatement pInsertStmt = null;
			PreparedStatement pUpdateStmt = null;
			PreparedStatement pDeleteStmt = null;
			Statement stmt = null;
			ResultSet rs = null;
			java.sql.Timestamp orderDate = new java.sql.Timestamp(System.currentTimeMillis());
			java.sql.Timestamp udfDate = null;
			ArrayList relArray = new ArrayList();
			String returnString = "";

			//Declaring fields of the table User_Rights
			String profileId = null;
			String application = null;
			String level1 = null, level2 = null, level3 = null, level4 = null, level5 = null;
			String menuName = null;
			String rights = null;
			String accFilt = null;
			String defFilt = null;
			String objName = null;

			NodeList parentNodeList = null;
			NodeList childNodeList = null;
			Node parentNode = null;
			Node childNode = null;
			String childNodeName = "";

			boolean bDetailFound = false;
			int parentNodeListLength = 0;
			int childNodeListLength = 0;
			String delSql = "";
			String actualIssue="",workOrder="";
			String locationCodeFromUser="";
			String tranId="",lineNo="";


			//locCode =genericUtility.getColumnValue("loc_code_wip", headerDom);
			String batchUpdateSql = "UPDATE workorder_issdet SET " +
									"	loc_code__wip = ? ,		" +
									"	actual_issue = 'N'     "+
									"   where tran_id= ? and line_no=? ";

			String searchKey = null;
			int operation = 0;

		try
		{
				if(conn == null)
				{
					connDriver = new ConnDriver();
					conn = connDriver.getConnectDB("DriverITM");
					conn.setAutoCommit(false);
					connDriver = null;
					pUpdateStmt = conn.prepareStatement(batchUpdateSql);

				}

				parentNodeList = detailDom.getElementsByTagName("Detail2");
				parentNodeListLength = parentNodeList.getLength();

				for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
				{
					operation = 0;
					parentNode = parentNodeList.item(selectedRow);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();

					for (int childRow = 0; childRow < childNodeListLength; childRow++)
					{

						childNode = childNodeList.item(childRow);
						childNodeName = childNode.getNodeName();

						if (childNodeName.equals("loc_code__wip"))
						{
							if (childNode.getFirstChild() != null) // ****************
							{
								locationCodeFromUser = (childNode.getFirstChild().getNodeValue()).trim();

							}

						}
						else if (childNodeName.equals("tran_id"))
						{
							if (childNode.getFirstChild() != null) // ****************
							{
							    //the trim has been removed as it was not updating in old frame work//
								
								tranId = (childNode.getFirstChild().getNodeValue());

							}

						}
						else if (childNodeName.equals("line_no"))
						{
							if (childNode.getFirstChild() != null) // ****************
							{
								lineNo = (childNode.getFirstChild().getNodeValue()).trim();

							}

						}



					}
					if(locationCodeFromUser!=null && locationCodeFromUser.trim().length()>0)
					{
					  pUpdateStmt.setString(1, locationCodeFromUser);
					 
					  pUpdateStmt.setString(2, tranId);
					  pUpdateStmt.setInt(3, Integer.parseInt(lineNo));
					  pUpdateStmt.addBatch();
					}


			    }//outer for
    		pUpdateStmt.executeBatch();
			
			conn.commit();
			System.out.println("After Commit");
		}
		catch(BatchUpdateException be)
		{
			be.printStackTrace();
			returnString = be.getMessage();
			System.out.println("BatchUpdateException :RunMRPPrcEJB: CreatePlanDemand(ADPElement)" + returnString);
			System.out.println("Detail Exception : " + be.getNextException());
		}
		catch (SQLException ex)
		{
			returnString = ex.getMessage();
			try{conn.rollback();
			}catch(Exception e){}
			ex.printStackTrace();

		}
		catch (Exception e)
		{
			returnString = e.getMessage();
			try{
				conn.rollback();
			}catch(Exception ec){}

			e.printStackTrace();
		}
		finally
		{
			try
			{

				if(pUpdateStmt!=null)
				{
				 pUpdateStmt.close();
				 pUpdateStmt = null;
				}
                if(conn!=null)
				{
				 conn.close();
				 conn = null;
				}
			}catch(Exception e)
			{
			    e.printStackTrace();
			}
			
		}

		if (returnString == null || returnString.trim().length() == 0)
		{
			System.out.println("errString is null************** ");
			returnString="VTCOMPL";
			returnString = itmDBAccessEJB.getErrorString("",returnString,"","",conn);
			
		}
		else
		{
			System.out.println("errString is not  null ***************");
			returnString="VTPRCERR";
			returnString = itmDBAccessEJB.getErrorString("",returnString,"","",conn);
			
		}

         return returnString;
	}// end of process

	/*	1 - insert
		2- update
		3-delete
		Searches HashMap for availability of rights for searchKey
		if Not Found and rights is not null then
			return 1
		else if Found and rights is not null then
			return 2
		else if Found and rights = null
			return 3
	*/



}//class




