package ibase.webitm.ejb.fin;

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

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

import javax.ejb.Stateless;
import org.w3c.dom.Document;

@Stateless
public class MiscVchEmpPostSave extends ValidatorEJB implements MiscVchEmpPostSaveLocal,MiscVchEmpPostSaveRemote{
	public String postSave(String xmlString,String tranId,String editFlag, String xtraParams,Connection conn) throws RemoteException,ITMException
	{		
		System.out.println("xml String--->>["+xmlString+"]");
		Document dom = null;
		String errString="";
		
		try
		{
			if (xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);				
				errString = postSave(dom,tranId,xtraParams,conn);
			}
			
		}
		catch(Exception e)
		{
			System.out.println("Exception : MiscVchEmpPostSave.java : postSave : ==>\n"+e.getMessage());
			throw new ITMException(e);
		}		
		return errString;
	}
	
	
	public String postSave(Document dom,String tranId,String xtraParams,Connection conn)
	{

		System.out.println("in MiscVchEmpPostSave postSave tran_id---->>["+tranId+"]");
		ResultSet rs=null;
		PreparedStatement pstmt=null;
		String sql="",errorString="";
		double sumAmount=0;	
		int count=0;
		try{	

			tranId = GenericUtility.getInstance().getColumnValue("tran_id",dom);
			System.out.println("tran_id123--->>["+tranId+"]");
			sql="select sum(amount) from misc_vch_empdet where tran_id = ?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs=pstmt.executeQuery();
			if(rs.next()){
				sumAmount=rs.getDouble(1);
			}
			System.out.println("sumAmount---->>["+sumAmount+"]");
			if (pstmt != null){
	    	pstmt.close();
			pstmt=null;
		    }
			if (rs !=null){
			rs.close();
			rs=null;
			}
			
			
			sql="update misc_vch_emp set total_amount = ? where tran_id = ?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setDouble(1, sumAmount);
			pstmt.setString(2, tranId);
			count=pstmt.executeUpdate();
			if(count > 0){
				conn.commit();
			}else{
				conn.rollback();
			}
			System.out.println("post count---->>["+count+"]");
			
			
		}
		catch(Exception e){
			System.out.println("Exception : MiscVchEmpPostSave -->["+e.getMessage()+"]");
			e.printStackTrace();
			try{
			conn.rollback();
			}catch(Exception e1){
				System.out.println("Exception while rollbacking transaction....");
				e1.printStackTrace();
			}
		}
		return errorString;
	
	}
}
