package ibase.utility.training;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Random;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import ibase.bi.common.system.config.DBInfo;
import ibase.ejb.CommonDBAccessEJB;
import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseException;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.utility.ITMException;

public class GenerateXml extends ActionHandlerEJB {

	/* 
	 * */
	public String actionHandler(String tranID, String xtraParam, String forceFlag) throws RemoteException, ITMException {
		String retVal = "";	
		BaseLogger.log("3",null,null,"Inside actionHandler.. ");
		BaseLogger.log("3",null,null,"Inside actionHandler.. tranID[ " + tranID + "]"); //P2BPH0125
		BaseLogger.log("3",null,null,"Inside actionHandler.. xtraParam" + xtraParam);
		BaseLogger.log("3",null,null,"Inside actionHandler.. forceFlag" + forceFlag);

		try {
			updatePaymentStatus(tranID, xtraParam);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return retVal;
	}
	
	//Method to update Payment Status, this method will get called from Confirm Action of misc_pay. 
	//Thr is a need to be called from other places as well as while receiving the staus update from Bank, So need to ensure this accomodates that as well
	//Mostly may get called from Scheduler - thr user may be the generic here, 
	//but while calling from action user will be the person who called the confirmation
	private void updatePaymentStatus(String tranID, String xtraParam) throws Exception {
		BaseLogger.log("3",null,null,"Inside updatePaymentStatus.. ");

		try {
			E12GenericUtility e12GenericUtility = new E12GenericUtility();
			CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
			
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext initialContext = new InitialContext(appConnect.getProperty());
			
			Connection connection = null;

		
			String userCode = e12GenericUtility.getValueFromXTRA_PARAMS(xtraParam, "loginCode");
			UserInfoBean userInfo = commonDBAccessEJB.createUserInfo(userCode);
			ConnDriver connDriver = new ConnDriver();
            connection = connDriver.getConnectDB(userInfo.getTransDB());
            
            StringBuffer processDynXmlString=new StringBuffer();
			processDynXmlString.append("<DocumentRoot><description>Datawindow Root</description><group0>");
			processDynXmlString.append("<description>Group0 description</description><Header0><description>Header0 members</description>");
			processDynXmlString.append("<objName><![CDATA[payintstatus]]></objName>");
			processDynXmlString.append("<pageContext><![CDATA[1]]></pageContext>");
			processDynXmlString.append("<objContext><![CDATA[1]]></objContext>");
			processDynXmlString.append("<editFlag><![CDATA[A]]></editFlag>");
			processDynXmlString.append("<focusedColumn><![CDATA[]]></focusedColumn>");
			processDynXmlString.append("<action><![CDATA[SAVE]]></action>");
			processDynXmlString.append("<elementName><![CDATA[]]></elementName>");
			processDynXmlString.append("<keyValue><![CDATA[1]]></keyValue>");
//			processDynXmlString.append("<taxKeyValue><![CDATA[]]></taxKeyValue>");
			processDynXmlString.append("<saveLevel><![CDATA[1]]></saveLevel>");
			processDynXmlString.append("<forcedSave><![CDATA[false]]></forcedSave>");
			processDynXmlString.append("<Detail1 dbID='' domID='1'  objContext='1'  objName='payintstatus'>");
			processDynXmlString.append("<attribute IS_CHANGE='Y' pkNames='TRAN_ID' selected='N' status='N' updateFlag='A'/>");
			
//			processDynXmlString.append("<taxInFocus><![CDATA[false]]></taxInFocus>");
			
			
			//  TO GET REFSER
			String refser = "";

			DBAccessEJB dbAccessEJB = new DBAccessEJB();
			try 
			{
				refser = dbAccessEJB.getDBColumnValue("TRANSETUP", "REF_SER", "TRAN_WINDOW  = 'w_misc_pay'", userInfo.getTransDB());
				BaseLogger.log("3",null,null,"Value of refser... ["+refser +"]");

			} 
			catch (RemoteException | ITMException e) 
			{
				e.printStackTrace();
			}
			
	
			
			processDynXmlString.append(getTransXML(tranID, refser, "Payment Initiated", "", ""));
			
			processDynXmlString.append("</Detail1>");
			processDynXmlString.append("</Header0></group0></DocumentRoot>");
			String XmlString = processDynXmlString.toString();
			BaseLogger.log("3",null,null," Xml String... "+XmlString);


			
			//call the process request here
			MasterStatefulLocal masterStateful = (MasterStatefulLocal)initialContext.lookup("ibase/MasterStatefulEJB/local");
			String reString = masterStateful.processRequest( getUserInfo(), XmlString, false, connection);  //userInfo --pass
			BaseLogger.log("3",null,null,"reString.. "+ reString);

		}
		catch(Exception e) {
			throw e;
		}
		
	}
	
	/*
	 * 
	 * */
	private String getTransXML(String paymentTranID, String refSer, String descr, String remarks, String errorDet) 
	{
		//Need to generate XML for payIntStatus
		
		StringBuffer transXML = new StringBuffer();
		
		//transXML.append("<tran_id><![CDATA[]]></tran_id>");
	//	transXML.append("<TRAN_ID><![CDATA[gsb]]></TRAN_ID>");
		transXML.append("<ref_ser><![CDATA["+ refSer +"]]></ref_ser>");
		transXML.append("<ref_id><![CDATA["+ paymentTranID +"]]></ref_id>");
		transXML.append("<status_date><![CDATA["+ getCurrentDate() +"]]></status_date>");
		transXML.append("<stage_descr><![CDATA["+ descr +"]]></stage_descr>");
		transXML.append("<remarks><![CDATA["+ remarks +"]]></remarks>");
		transXML.append("<error_det><![CDATA["+ errorDet +"]]></error_det>");
	
		return transXML.toString();
	}

	private InitialContext getInitialContext() throws ITMException {

		InitialContext ctx = null;
		try {
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
		} catch (ITMException itme) {
			BaseLogger.log("0", null, null, "ITMException : getInitialContext : " + itme.getMessage());
			throw itme;
		} catch (Exception e) {
			BaseLogger.log("0", null, null, "Exception : getInitialContext : " + e.getMessage());
			throw new ITMException(e);
		}
		return ctx;
	}
	
	 public static String getCurrentDate()
		{
			BaseLogger.log("3", null, null, "inside getCurrentDate .. ");

			LocalDate currentDate = LocalDate.now();
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yy");
			BaseLogger.log("3", null, null, "currentDate is .. [" + currentDate.format(formatter) + "]");
			return currentDate.format(formatter);

		}

	
}