/********************************************************
	Title 	 : DistRcpExShConf
	Date  	 : 13/MAR/15
	Developer: Pankaj R.
 ********************************************************/

package ibase.webitm.ejb.dis;

//import java.awt.geom.Arc2D.Double;
import java.rmi.RemoteException;
import java.sql.*;

import ibase.ejb.*;

import ibase.webitm.ejb.*;
import ibase.system.config.*;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;


@Stateless

public class DistRcpExShConf extends ActionHandlerEJB implements DistRcpExShConfLocal,DistRcpExShConfRemote //SessionBean
{
	public String confirm(String tranId,String xtraParams,String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("Inside Confirm Method");

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "",sql1="";
		String siteCode="";
		ConnDriver connDriver = null;
		String loginEmpCode = "";
		String confirm = "",empCodeAprv="" ;
		String errString = ""; 
		int updateCount=0;
		double shortageAmtHdr=0.0,shortAmtVal=0.0;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ValidatorEJB validatorEJB = null;
		DistCommon distCommom = null; 

		ITMDBAccessEJB itmDBAccessEJB = null;
		try
		{
			itmDBAccessEJB = new ITMDBAccessEJB();
			validatorEJB = new ValidatorEJB();
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			conn.setAutoCommit(false);
			empCodeAprv = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			System.out.println("empCodeAprv@@@@@@@"+empCodeAprv);
			
			sql = "select confirmed,site_code,shortage_amt from distrcp_exsh_hdr where tran_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,tranId);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				confirm = rs.getString("confirmed");
				siteCode = rs.getString("site_code");
				shortageAmtHdr=rs.getDouble("shortage_amt");
			}
			System.out.println("Cconfirm@@@@@@@@"+confirm);
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			if(confirm != null && confirm.equalsIgnoreCase("Y"))
			{
				System.out.println("The Selected transaction is already confirmed");
				errString = itmDBAccessEJB.getErrorString("","VTMCONF1","","",conn);
				return errString;
			}
			else /*(confirm != null  && confirm.equalsIgnoreCase("N") */
			{
                 //comment for test
				sql = "update distrcp_exsh_hdr set confirmed = 'Y', conf_date = ?,emp_code__aprv = ? where tran_id = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
				pstmt.setString(2, empCodeAprv);
				pstmt.setString(3, tranId);
				updateCount = pstmt.executeUpdate();
				System.out.println("no of row update: "+updateCount);
				System.out.println("Date@@@@@@@@@"+new java.sql.Date(new java.util.Date().getTime()));
				System.out.println("empCodeAprv+empCodeAprv"+empCodeAprv);
				System.out.println("tranId@@@@@@@@@"+tranId);
				pstmt.close();
				pstmt = null;
								
				/*if(updateCoount > 0)// comment added by sagar on 18/05/15 
				{
					errString = itmDBAccessEJB.getErrorString("","VTSTATSUBM ","","",conn);
				}
				*/
				
				if(updateCount > 0) //code added by sagar on 13/05/15
				{
					System.out.println(">>In Submit If update successfully then send intimation mail with report>>>");
					errString= sendMailReport(tranId,siteCode,shortageAmtHdr,xtraParams,conn);
					System.out.println(">>>>In DistRcpExShConf after sendMailReport() errString:"+errString);
				}	
				System.out.println(">>>>>>>Check errString:"+errString);
				if((errString != null) &&  errString.indexOf("REPORTSUCC") > -1)
				{
					errString = itmDBAccessEJB.getErrorString("","VTSTATSUBM","","",conn);
				}
				else
				{
					errString = itmDBAccessEJB.getErrorString("","VTFAILSUBM","","",conn);
				}
			}
		}
		
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			errString = GenericUtility.getInstance().createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println(">>>>>In finally errString:"+errString);
				if(errString != null && errString.trim().length() > 0)
				{
					if(errString.indexOf("VTSTATSUBM") > -1)
					{
						conn.commit(); 
					}
					else
					{
						conn.rollback();
					}
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				conn.close();
			}
			catch(Exception e)
			{
				System.out.println("Exception : "+e);e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	
	}//end of confirm method
	
 
	//method added by sagar on 19/05/15 
	public String sendMailReport(String tranId, String siteCode,double shortageAmtHdr,String xtraParams,Connection conn) throws ITMException
	{
		String retString="";
		String xmlString="",reportName="",reportArgs="",reportType="",formatCode="",shortAmtValStr="";
		double shortAmtVal=0.0;
		DistCommon distCommom = null;
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			distCommom = new DistCommon(); 
			System.out.println(">>>>In sendMailReport method>>>");
			E12ReportComp reportComp= new E12ReportComp();
			reportName="d_distrcp_exc_shrt";
			reportArgs="tran_id.String:tran_id,user_id.String:as_user_id,site_code.String:as_site";
			reportType="PDF";
			formatCode="DOM_REG";
			shortAmtValStr = checkNull(distCommom.getDisparams("999999", "SHORT_AMT_VAL", conn));
			System.out.println(">>>>>In mail tranId:"+tranId);
			System.out.println(">>>>>In mail siteCode:"+siteCode);
			System.out.println(">>>>>In mail shortageAmtHdr:"+shortageAmtHdr);
			System.out.println(">>>>>In mail shortAmtValStr:"+shortAmtValStr);
			if(shortAmtValStr!=null && shortAmtValStr.trim().length() > 0 && !shortAmtValStr.equals("NULLFOUND") )
			{
			     shortAmtVal = Double.parseDouble(shortAmtValStr);
			     System.out.println(">>>>>>>>Disparm shortAmtVal:"+shortAmtVal);
			}
			if(shortageAmtHdr > shortAmtVal)
			{
				formatCode="DRCPSH_1"; // send mail for 'To' and 'Cc'.
				System.out.println(">>>shortAmtVal is greater than disparm value then formatCode is:"+formatCode);
			}
			else
			{
				formatCode="DRCPSH";// send mail only for 'To'.
				System.out.println(">>>shortAmtVal is less than disparm value then formatCode is:"+formatCode);
			}
			System.out.println(">>>>>>>>formatCode:"+formatCode);
			StringBuffer xmlBuff = null;
			xmlBuff = new StringBuffer();
					
			xmlBuff.append("<?xml version='1.0' encoding='UTF-8'?>\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("distrcp_exsh").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("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
			xmlBuff.append("<forcedSave><![CDATA[").append(true).append("]]></forcedSave>");
			xmlBuff.append("<description>").append("Header0 members").append("</description>");
			xmlBuff.append("<Detail1 objContext=\"1\" objName=\"distrcp_exsh\" domID=\"\" dbID=\"\">");
			xmlBuff.append("<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>");
			xmlBuff.append("<tran_id><![CDATA["+ tranId +"]]></tran_id>");
			xmlBuff.append("<site_code><![CDATA["+ siteCode +"]]></site_code>");
			xmlBuff.append("</Detail1>");
			xmlBuff.append("</Header0>");
			xmlBuff.append("</group0>");
			xmlBuff.append("</DocumentRoot>");
			
			xmlString = xmlBuff.toString();
			System.out.println(">>>>>>>>>>xmlString for sendReport:"+xmlString);
			retString= reportComp.sendReport(xmlString, reportName, reportArgs, reportType, formatCode, xtraParams);
			System.out.println(">>>retString from sendReport:"+retString);
		}
		catch(Exception e)
		{
			retString = e.getMessage();
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retString;
	}
	private String checkNull(String input)
	{
		if (input == null) 
		{
			input = "";
		}
		return input.trim();
	}
	private String getObjNameFromDom( Document dom, String attribute ) throws RemoteException,ITMException //for test 
	{
		NodeList detailList = null;
		Node currDetail = null;
		String objName = "";
		int detailListLength = 0;

		try
		{
			detailList = dom.getElementsByTagName("Detail1");
			detailListLength = detailList.getLength();
			for (int ctr = 0; ctr < detailListLength; ctr++)
			{
				currDetail = detailList.item(ctr);
				objName = currDetail.getAttributes().getNamedItem(attribute).getNodeValue();
			}
		}
		catch ( Exception e )
		{
			throw new ITMException(e);
		}
		System.out.println("objName =["+objName+"]");
		return objName;
	}

}//end of class
