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 java.text.SimpleDateFormat;
import javax.ejb.EJBObject;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.ITMException;
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


//public class CopyOrgStructureEJB extends ProcessEJB implements SessionBean
@Stateless // added for ejb3

public class CopyProcRoute extends ProcessEJB implements CopyProcRouteLocal, CopyProcRouteRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	CommonConstants commonConstants = new CommonConstants();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	String processStr = null;

	ProcStructRec structRec = null;
	ArrayList procStructList = null;

	/*public void ejbCreate() throws RemoteException, CreateException
	{
	}
	public void ejbremove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	
	public String process() throws RemoteException,ITMException
	{
		System.out.println("Called Empty process");
		return "";
	}
	//process()
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		
		System.out.println("!!!!!!!! PROCESS IS GOING TO BE START !!!!!!!!!!");
		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 :CopyProcRouteEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("******** PROCESS IS STARTED *********");
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = null;
		Connection conn = null;
		PreparedStatement stmt = null;
		PreparedStatement pStmt = null;
		PreparedStatement pInsStruct = null;
		ResultSet rs = null;
		String routeCodeFrom = null;
		String routeCodeTo = null;
		String retString = "" ;
		String errString = "";
		String errCode = "";
		String returnString = "";
		String lsErrcode = "";
		String tableNo ="";
		String stanCode = "";
		String shDescr = "";
		String chgUser = "";
		String userId = null;
		String chgTerm = "";
	
		String sql = null;
		
		
		try
		{
			procStructList = new ArrayList();
			
			
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "DriverITM" );
			conn.setAutoCommit( false );
			connDriver = null;
			
			routeCodeFrom =	genericUtility.getColumnValue("route_code__from", headerDom); 
			routeCodeTo =	genericUtility.getColumnValue("route_code__to", headerDom);
		  
		   
			chgUser = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" ); 
			chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "termId" );
			System.out.println( "**********chgUser**********" + chgUser );
			userId = chgUser;
			System.out.println( "**********chgTerm**********" + chgTerm );
			routeCodeFrom =	genericUtility.getColumnValue( "route_code__from", headerDom );
			routeCodeTo =	genericUtility.getColumnValue( "route_code__to", headerDom );
			System.out.println("**********Version Old :: "  + routeCodeFrom);
			System.out.println("**********Version New :: "  + routeCodeTo);
		
			if(routeCodeFrom == null || routeCodeFrom.trim().length()== 0)
			{
				errString = itmDBAccessEJB.getErrorString( "", "RCNULL", userId );
				System.out.println("@@@@@@@@@ errString@@@@@@@@" +errString);
				return errString;
			}
			if(routeCodeTo == null || routeCodeTo.trim().length()== 0)
			{
				errString = itmDBAccessEJB.getErrorString( "", "RCNULL", userId );
						return errString;
			   
			}
			if(routeCodeFrom.equals(routeCodeTo))
			{
			   errString = itmDBAccessEJB.getErrorString( "", "RCEQL", userId );
			   //errString = itmDBAccessEJB.getErrorString("","RCEQL","","",conn);
			   System.out.println("%%%%%%%%%% errString %%%%%%%%%%%" +errString);
			   return errString;
			}
			
			sql = "SELECT OPERATION, DESCR, PROC_CODE, SEQ_NO,WORK_CTR, MC_CODE,"+
				  "WAIT_TIME, SET_TIME, RUN_TIME, RESET_TIME, PROCESS_SIZE, QC_REQD, "+
				  "OPERATION_LEVEL, QC_TYPE, DEPT_CODE, AUTO_ISSUE, COMMENTS, SITE_CODE "+
				  "FROM PROCROUTE WHERE ROUTE_CODE='"+routeCodeFrom+"'";
			pStmt = conn.prepareStatement( sql );
			System.out.println("sqlStr is =========> " +sql);
			rs = pStmt.executeQuery();
			while( rs.next() )
			{
				structRec = new ProcStructRec();
				structRec.operation = rs.getInt( "OPERATION" );;
				structRec.desc = rs.getString( "DESCR" );
				structRec.procCode = rs.getString( "PROC_CODE" );
				structRec.seqNO = rs.getString( "SEQ_NO" );
				structRec.workCtr = rs.getString( "WORK_CTR" );
				structRec.mcCode = rs.getString( "MC_CODE" );
				structRec.waitTime = rs.getInt( "WAIT_TIME" );
				structRec.setTime = rs.getInt( "SET_TIME" );
				structRec.runTime = rs.getInt( "RUN_TIME" );
				structRec.resetTime = rs.getInt( "RESET_TIME" );
				structRec.processSize = rs.getInt( "PROCESS_SIZE" );
				structRec.qcReqd = rs.getString( "QC_REQD" );
				structRec.operationLevel = rs.getInt( "OPERATION_LEVEL" );
				structRec.qcType = rs.getString( "QC_TYPE" );
				structRec.deptCode = rs.getString( "DEPT_CODE" );
				structRec.autoIssue = rs.getString( "AUTO_ISSUE" );
				structRec.comments = rs.getString( "COMMENTS" );
				structRec.siteCode = rs.getString( "SITE_CODE" );
				procStructList.add( structRec );
				structRec = null;
			}
			rs.close();
			rs = null;
			pStmt.close();
			pStmt = null;
			
			sql = " INSERT INTO PROCROUTE ("+
					"ROUTE_CODE, OPERATION, DESCR, PROC_CODE, SEQ_NO,WORK_CTR, MC_CODE,"+
					"WAIT_TIME, SET_TIME, RUN_TIME, RESET_TIME, PROCESS_SIZE, QC_REQD,"+
					"OPERATION_LEVEL, QC_TYPE, DEPT_CODE, AUTO_ISSUE, COMMENTS, SITE_CODE,"+
					"CHG_DATE,CHG_USER, CHG_TERM)"+
					"VALUES (			"+
					"		?, ?, ?, ?, ?,?,?,"+
					"		?, ?, ?, ?, ?,?,"+
					"		?, ?, ?, ?, ?,?,"+
					"		?, ?, ? )" ; 
			pInsStruct = conn.prepareStatement( sql );
			
			System.out.println("insOrgStructSql :: " + sql );
			
			errCode = null;
			
			for( int structIdx = 0,
					stuctListLen = procStructList.size(); structIdx < stuctListLen ; structIdx++ )
			{
				structRec = ( ProcStructRec )procStructList.get( structIdx );

				pInsStruct.setString( 1, routeCodeTo );
				pInsStruct.setInt( 2, structRec.operation );
				pInsStruct.setString( 3, structRec.desc );
				pInsStruct.setString( 4, structRec.procCode );
				pInsStruct.setString( 5, structRec.seqNO );
				pInsStruct.setString( 6, structRec.workCtr );
				pInsStruct.setString( 7, structRec.mcCode );
				pInsStruct.setInt( 8, structRec.waitTime );
				pInsStruct.setInt( 9, structRec.setTime );
				pInsStruct.setInt( 10, structRec.runTime );
				pInsStruct.setInt( 11, structRec.resetTime );
				pInsStruct.setInt( 12, structRec.processSize );
				pInsStruct.setString( 13, structRec.qcReqd );
				pInsStruct.setInt( 14, structRec.operationLevel );
				pInsStruct.setString( 15, structRec.qcType );
				pInsStruct.setString( 16, structRec.deptCode );
				pInsStruct.setString( 17, structRec.autoIssue );
				pInsStruct.setString( 18, structRec.comments );
				pInsStruct.setString( 19, structRec.siteCode );
				pInsStruct.setTimestamp(20,new Timestamp(System.currentTimeMillis()));
				pInsStruct.setString( 21, chgUser );
				pInsStruct.setString( 22, chgTerm );
				
				pInsStruct.addBatch();
			}
			
			pInsStruct.executeBatch();
			pInsStruct.close();
			pInsStruct =null;
			
			
			
		}    					
		catch(SQLException ex)
		{
			errCode = "VTSQLEXC";
			ex.printStackTrace();  
			System.out.println("Exception in Process1 :: " + ex.getMessage());
			
			return errString;
			
		}
		catch(Exception e)
		{
			errCode = "VTPRCERR";
			e.printStackTrace();  
			System.out.println("Exception in Process2 :: " + e.getMessage());
			   
		}
		finally
		{
			try
			{
				if( pInsStruct != null )
				{
					pInsStruct.close();
				}
				pInsStruct =null;
				
				
				if( errCode == null || errCode.trim().length() == 0 )
				{
					errCode = "VTCOMPL";
					conn.commit();
					System.out.println("Transaction Commit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				}
				else
				{
					errCode = "VTPRCERR";
					conn.rollback();
					System.out.println("Transaction RollBack!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				} 
				
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Error In closing connection::==> "+e);
				e.printStackTrace();
			}
		}
		errString =	itmDBAccessEJB.getErrorString( "", errCode, userId );
	
	    return errString;
    }//END OF PROCESS
	private class ProcStructRec
	{
		int operation = 0;
		String desc = null;
		String procCode = null;
		String seqNO = null;
		String workCtr = null;
		String mcCode = null;
		int waitTime = 0;
		int setTime = 0;
		int runTime = 0;
		int resetTime = 0;
		int processSize = 0;
		String qcReqd = null;
		int operationLevel = 0;
		String qcType = null;
		String deptCode = null;
		String autoIssue = null;
		String comments = null;
		String siteCode = null;
	}
	
	
 } // END OF EJB 