package ibase.webitm.ejb.sys;

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.utility.GenericUtility;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.utility.ITMException;
import ibase.wrkflw.utility.WorkflowLogger;

import java.io.ByteArrayInputStream;
import java.io.OutputStreamWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ejb.Stateless;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class CallConfirmService extends ActionHandlerEJB implements CallConfirmServiceLocal,CallConfirmServiceRemote {

	final String XTRA_PARAMS_SEPARATOR = "~~";
	
	@Override
	public String confirm(String objName, String tranID, String xtraParams,	String forcedFlag) throws RemoteException, ITMException 
	{
		Connection  connectionObject = null;
		String retString = "";
		try
		{
			retString =  confirmRecord(objName,tranID,connectionObject,xtraParams,forcedFlag);
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("Returning Result ::"+retString);
		return retString;
	}
	
	public String confirmRecord(String businessObj,String tranID ,Connection conn, String refSer, String forcedFlag) throws ITMException
	{
		String methodName = "gbf_post";
		String actionURI="",sql="",serviceCode="",compName="",serviceURI="",retString="";
		PreparedStatement pStmtSysEvent =null ,pStmtSysEvService=null ;
		ResultSet rsSysEvent,rsSysEvService;
		String xtraParams ="";
		try{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			GenericUtility genericUtility = GenericUtility.getInstance();
			xtraParams = getExtraParams(tranID,refSer,conn);
			actionURI = "http://NvoServiceurl.org/" + methodName;
			
			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'pre_confirm' ";
			pStmtSysEvent = conn.prepareStatement(sql);
			pStmtSysEvent.setString(1,businessObj);
			rsSysEvent = pStmtSysEvent.executeQuery();
			if ( rsSysEvent.next() )
			{
				serviceCode = rsSysEvent.getString("SERVICE_CODE");
				compName = rsSysEvent.getString("COMP_NAME");
			}
			
			pStmtSysEvent.close();
			pStmtSysEvent = null;
			rsSysEvent.close();
			rsSysEvent = null;
			
			System.out.println("===========serviceCode========= = "+serviceCode+" compName "+compName);
			
			sql = "SELECT SERVICE_URI,METHOD_NAME FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
			pStmtSysEvService = conn.prepareStatement(sql);
			pStmtSysEvService.setString(1,serviceCode);
			rsSysEvService = pStmtSysEvService.executeQuery();
			if ( rsSysEvService.next() )
			{
				serviceURI = rsSysEvService.getString("SERVICE_URI");
				methodName=rsSysEvService.getString("METHOD_NAME");
			}
			
			pStmtSysEvService.close();
			pStmtSysEvService = null;
			rsSysEvService.close();
			rsSysEvService = null;
			
			
			System.out.println("==============serviceURI=========== = "+serviceURI+" compName = "+compName);
			
			Service service = new Service();
			Call call = (Call)service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(serviceURI));
			call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(actionURI);
			
			Object[] aobj = new Object[4];

			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tran_id"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "forced_flag"), XMLType.XSD_STRING, ParameterMode.IN);

			aobj[0] = new String(compName);
			aobj[1] = new String(tranID);
			aobj[2] = new String(xtraParams);
			aobj[3] = new String(forcedFlag);

			call.setReturnType(XMLType.XSD_STRING);
			retString = (String)call.invoke(aobj);
			System.out.println("Return string from NVO is:==>["+retString+"]");
			Document dom= parseString(retString);
			String errCode = getErrorCode(dom);
			retString = new ibase.webitm.ejb.ITMDBAccessEJB().getErrorString("",errCode,"");
			System.out.println("Return string from ITMDBAccessEJB() is:==>["+retString+"]");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (pStmtSysEvent != null )
				{
					pStmtSysEvent.close();
					pStmtSysEvent = null;
				}
				if (pStmtSysEvService != null )
				{
					pStmtSysEvService.close();
					pStmtSysEvService = null;
				}
				if( conn != null ){
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{}
		}
		
		return retString;
	}
	
	public Document parseString(String xmlString)throws ITMException
	{
		Document dom = null;
		try
		{
			//Changed by Monif on 2/23/2009 [For special char parsing issue].Start
			ibase.utility.GenericUtility genericUtility = new ibase.utility.GenericUtility();
			xmlString = genericUtility.setXmlDec( xmlString );			
			//Changed by Monif on 2/23/2009 [For special char parsing issue].End	
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setIgnoringComments(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			OutputStreamWriter errorWriter =   new OutputStreamWriter(System.err, CommonConstants.ENCODING);
			ByteArrayInputStream baos = new ByteArrayInputStream(xmlString.getBytes());
			dom = db.parse(baos);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return dom;
	}
	
	private String getErrorCode(Document dom)
	{
		NodeList detailList = null;
		Node currDetail = null;
		NodeList currDetailList = null;
		String nodeName = "";  
		int currDetailListLength = 0;
		int	detailListLength = 0;
		String errCode="";

		detailList = dom.getElementsByTagName("Errors");
		detailListLength = detailList.getLength();
		if ( detailListLength > 0 )
		{
			for (int ctr = 0;ctr < detailListLength;ctr++)
			{
				currDetail = detailList.item(ctr);
			}
			currDetailList = currDetail.getChildNodes();
			currDetailListLength = currDetailList.getLength();
			for (int i=0;i< currDetailListLength;i++)
			{
				Node item =currDetailList.item(i);
				nodeName = item.getNodeName();
				System.out.println("@@@@ nodeName :[ "+nodeName+" ]");
				if (nodeName.equalsIgnoreCase("error"))
				{
					errCode = currDetailList.item(i).getAttributes().getNamedItem("id").getNodeValue();
					System.out.println("@@@@ errCode found :[ "+errCode+" ]");
					break;
				}
			}
		}
		System.out.println("@@@@ errCode :[" + errCode+" ]");
		return errCode;
		
	}
	
	private String getExtraParams(String tranID,String refSer,Connection conn) throws ITMException
	{
		
		String xtraParam="";
		PreparedStatement pstmtExtraParm = null;
		ResultSet rsExtraParm=null;
		try{
			
			String sqlExtraParm= "SELECT EMP_CODE ,USER_ID__SIGN FROM OBJ_SIGN_TRANS WHERE REF_ID =? AND REF_SER = ? ORDER BY LINE_NO DESC";
			pstmtExtraParm = conn.prepareStatement(sqlExtraParm);
			pstmtExtraParm.setString(1, tranID);
			pstmtExtraParm.setString(2, refSer);
			rsExtraParm = pstmtExtraParm.executeQuery();
			
			if(rsExtraParm.next())
			{
				xtraParam = "loginCode=" + rsExtraParm.getString("USER_ID__SIGN") + XTRA_PARAMS_SEPARATOR + "loginEmpCode=" + rsExtraParm.getString("EMP_CODE") + XTRA_PARAMS_SEPARATOR + "runMode=I";
			}
			pstmtExtraParm.close();
			pstmtExtraParm = null;
			rsExtraParm.close();
			rsExtraParm = null;
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		finally
		{
			if(pstmtExtraParm != null)
			{
				try {
					pstmtExtraParm.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				pstmtExtraParm = null;
			}
			if(rsExtraParm != null)
			{
				try {
					rsExtraParm.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				rsExtraParm = null;
			}
		}
		
		return xtraParam;
	}
	
}
