package ibase.webitm.ejb.afsal;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import javax.naming.InitialContext;

import org.w3c.dom.Document;

import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.system.config.AppConnectParm;


public class SerReqPostSave extends ValidatorEJB {
    ActionHandlerEJB actionHandlerEJB = new ActionHandlerEJB();
	E12GenericUtility genericUtility = new E12GenericUtility();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	boolean isError = false;
	public String postSave(String xmlString,String editFlag, String xtraParams,Connection conn) throws RemoteException,ITMException
	{
	    BaseLogger.log("3", null, null, "In SerReqPostSave method 1");
		String retString = "";

		Document dom = null;
		E12GenericUtility genericUtility = null;
		try
		{
			genericUtility = new E12GenericUtility();
			dom = genericUtility.parseString(xmlString);
			System.out.println("xmlString-----------------"+xmlString);
			retString = postSave(dom,editFlag,xtraParams,conn);
			
		}
		catch(Exception e )
		{
			e.getMessage();
			e.printStackTrace();
			isError = true;
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(!isError)
				{
					conn.commit();
				}
				else
				{
					conn.rollback();
				}
			}
			catch(Exception e)
			{
				e.getMessage();
				e.printStackTrace();
				isError = true;
				throw new ITMException(e);
			}
		}
		return retString;
	}
	
	public String postSave(Document dom, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException {
	    BaseLogger.log("3", null, null, "In SerReqPostSave method::");
	    String errString="";
	    String errorString = "";
		String retString = "";
		String requestId = "";
		String TranType = "";
		String assignedBy = "";
		String remarks = "";
		String compDetails = "";
		String actionCode = "";
		String taskId = "";
		String assignedTo = "";
		StringBuffer xmlBuff = null;
		String currDateStr = "";
		String ticketNo = "";
		String reqDetails = "";
        String empCode = "";
        String reqType = "";
        String roleCodeAssign = "";
        String entityCode = "";
        String roleCodeSql = "";
        String loginSite = "";
		PreparedStatement roleCodePstmt = null;
		ResultSet roleCodeRs = null;
        String assignToSql = "";
		PreparedStatement assignToPstmt = null;
		ResultSet assignToRs = null;
		PreparedStatement insertPstmt = null;
		ResultSet insertRs = null;
		String sql = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;

	    try {
	    	requestId = checkNull(genericUtility.getColumnValue("req_id",dom));
		    ticketNo = checkNull(genericUtility.getColumnValue("ticket_no",dom));
		    reqDetails = checkNull(genericUtility.getColumnValue("dtl_descr",dom));
		    assignedBy = checkNull(genericUtility.getColumnValue("chg_user",dom));
		    reqType = checkNull(genericUtility.getColumnValue("req_type",dom));
			empCode = checkNull(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode"));
			BaseLogger.log("3", getUserInfo(), null,"requestId:"+requestId+" ticketNo:"+ticketNo+" reqDetails:"+reqDetails+" assignedBy:"+assignedBy+" reqType:"+reqType+" empCode:"+empCode );

			sql = "update ser_request set confirmed = 'Y' where req_id = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, requestId);
			int i = pstmt.executeUpdate();
			BaseLogger.log("3", null, null, "i is :"+i);
			conn.commit();
			pstmt.close();pstmt = null;
			java.sql.Timestamp currentDate = new java.sql.Timestamp(System.currentTimeMillis());
	    	SimpleDateFormat sdf3=new SimpleDateFormat( genericUtility.getApplDateFormat());//for xml 		
			currDateStr =  sdf3.format(currentDate);
			roleCodeSql = "select role_code__assign from ser_req_typ where req_type = ?";
			roleCodePstmt = conn.prepareStatement(roleCodeSql);
			roleCodePstmt.setString(1, reqType);
			roleCodeRs = roleCodePstmt.executeQuery();
			if(roleCodeRs.next())
			{
				roleCodeAssign = checkNull(roleCodeRs.getString("role_code__assign"));
			}
			BaseLogger.log("3", null, null, "roleCodeAssign is :"+roleCodeAssign);
			roleCodeRs.close();roleCodeRs = null;
			roleCodePstmt.close();roleCodePstmt = null;
			
			assignToSql = "select user_id from wf_role where role_code = ?";
			BaseLogger.log("3", null, null, "assignToSql is :"+assignToSql);

			assignToPstmt = conn.prepareStatement(assignToSql);
			assignToPstmt.setString(1, roleCodeAssign);
			assignToRs = assignToPstmt.executeQuery();
			if(assignToRs.next())
			{
				assignedTo = checkNull(assignToRs.getString("user_id"));
			}
			BaseLogger.log("3", null, null, "assignedTo is :"+assignedTo);

			assignToRs.close();assignToRs = null;
			assignToPstmt.close();assignToPstmt = null;
			
	    	xmlBuff = new StringBuffer();
			xmlBuff.append("<?xml version='1.0' encoding='ISO-8859-1'?>\n");
			xmlBuff.append("<DocumentRoot>");
			xmlBuff.append("<description>").append("Datawindow Root").append("</description>");
			xmlBuff.append("<group0>");
			xmlBuff.append("<description>").append("Group0 description").append("</description>");
			xmlBuff.append("<Header0>");
			xmlBuff.append("<objName><![CDATA[").append("ser_req_act").append("]]></objName>");  
			xmlBuff.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
			xmlBuff.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
			xmlBuff.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
			xmlBuff.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
			xmlBuff.append("<action><![CDATA[").append("SAVE").append("]]></action>");
			xmlBuff.append("<elementName><![CDATA[").append("").append("]]></elementName>");
			xmlBuff.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
			xmlBuff.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
			xmlBuff.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlBuff.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
			xmlBuff.append("<description>").append("Header0 members").append("</description>");	
			xmlBuff.append("<Detail1 dbID=\"\" domID=\"1\" objName=\"ser_req_act\" objContext=\"1\">");  
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<ser_req_act/>");
			xmlBuff.append("<tran_date><![CDATA["+ currDateStr +"]]></tran_date>");
			xmlBuff.append("<tran_type><![CDATA["+ "GEN" +"]]></tran_type>");
			xmlBuff.append("<req_id><![CDATA["+ requestId +"]]></req_id>");
			xmlBuff.append("<ticket_no><![CDATA["+ ticketNo +"]]></ticket_no>");
			xmlBuff.append("<dtl_descr><![CDATA["+ reqDetails +"]]></dtl_descr>");//complaint detail
			xmlBuff.append("<remarks><![CDATA["+ "Resolution auto created for request" +"]]></remarks>");
			xmlBuff.append("<emp_code><![CDATA["+ assignedBy +"]]></emp_code>");
			xmlBuff.append("<comp_code><![CDATA["+ "REQ0003" +"]]></comp_code>");
			xmlBuff.append("<comp_status><![CDATA["+ "L" +"]]></comp_status>");
			xmlBuff.append("<stdtime><![CDATA["+ "9" +"]]></stdtime>");
			xmlBuff.append("<planned_date><![CDATA["+ currDateStr +"]]></planned_date>");
			xmlBuff.append("<res_method><![CDATA["+ "R000000001" +"]]></res_method>");	//need to add
			xmlBuff.append("<chg_user><![CDATA["+ empCode +"]]></chg_user>");
			xmlBuff.append("<chg_date><![CDATA["+ currDateStr +"]]></chg_date>");
			xmlBuff.append("<action_id/>");
			xmlBuff.append("</Detail1>");		
			//end Request Resolution 

			
			
			sql = "select entity_code  from users where emp_code = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, assignedBy);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				entityCode = checkNull(rs.getString("entity_code"));
			}
			BaseLogger.log("3", null, null, "entityCode is :"+entityCode);

			rs.close();rs = null;
			pstmt.close();pstmt = null;
			//Request Resolution Details started --------------------------------------------<Details2>
			xmlBuff.append("<Detail2 dbID=\"\" domID=\"1\" objName=\"ser_req_act\" objContext=\"1\">");  
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<ser_req_act/>");
			xmlBuff.append("<line_no><![CDATA["+ 1 +"]]></line_no>");
			xmlBuff.append("<action_code><![CDATA["+ "SUP01" +"]]></action_code>");
			xmlBuff.append("<serviceplan><![CDATA["+ "OFS" +"]]></serviceplan>");
			xmlBuff.append("<assign_to__user><![CDATA["+ assignedTo +"]]></assign_to__user>");
			xmlBuff.append("<action_detl><![CDATA["+ "Resolution auto created for ticket" +"]]></action_detl>");
			xmlBuff.append("<entity_code><![CDATA["+ entityCode +"]]></entity_code>");
			xmlBuff.append("<stdtime><![CDATA["+ "9" +"]]></stdtime>");
			xmlBuff.append("<std_time><![CDATA["+ "9" +"]]></std_time>");
			xmlBuff.append("<planned_date><![CDATA["+ currDateStr +"]]></planned_date>");
			xmlBuff.append("<emp_code><![CDATA["+ assignedTo +"]]></emp_code>");
			//Remove "/" from date to set task ID--------
			String taskID = genericUtility.getValidDateString(currDateStr, genericUtility.getApplDateFormat(),  "dd/mm/yy");
			taskID = taskID.replace("/","");
			
			xmlBuff.append("<task_id><![CDATA["+ taskID +"]]></task_id>");	
			BaseLogger.log("3", null, null, "taskID is :"+taskID);
			
			xmlBuff.append("<action_type><![CDATA["+ 001 +"]]></action_type>");
			xmlBuff.append("<action_status><![CDATA["+ 1 +"]]></action_status>");
			xmlBuff.append("<action_id/>");
			xmlBuff.append("</Detail2>");
			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			//end ------------------------------------------------------------------
	
			errString = saveData(loginSite,xmlBuff.toString(),empCode, conn);
			BaseLogger.log("3", getUserInfo(), null,"Request Resolution Detial screen----" + errString);
			if (errString.indexOf("Success") < 0)
			{
				System.out.println(" [Request Resolution Details  Not Success@@ : : " + errString + "]");	
				isError = true;
				return errString;
			}
		    }catch (Exception e) {
				System.out.println("Exception :SerReqPostSave :" + e.getMessage() + ":");
				errorString = genericUtility.createErrorString(e);
			}

		return "";
	}
	
	private String saveData(String siteCode,String xmlString,String userId, Connection conn) throws ITMException
	{
		System.out.println("saving data...........");
		InitialContext ctx = null;
		String retString = null;
		MasterStatefulLocal masterStateful = null; // for ejb3
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			ctx = new InitialContext(appConnect.getProperty());
			masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
			System.out.println("-----------masterStateful------- " + masterStateful);
			String [] authencate = new String[2];
			authencate[0] = userId;
			authencate[1] = "";
			System.out.println("xmlString to masterstateful [" + xmlString + "]");
			retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
			System.out.println("--retString - -"+retString);

			//masterStatefulLocal = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local"); 
			//System.out.println("masterstatement process request....qqq:: "+masterStatefulLocal);
			//retString = masterStatefulLocal.processRequest( authencate, siteCode, true, xmlString.toString(),false,conn);
		}
		catch(ITMException itme)
		{
			System.out.println("ITMException :CreateAssetInstall :saveData :==>");
			throw itme;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception :CreateAssetInstall :saveData :==>");
			throw new ITMException(e);
		}
		return retString;
	}

	
	private String checkNull(String input) {
		if (input == null) {
			input = "";
		} else {
			input = input.trim();
		}
		return input;
	}
}