package ibase.webitm.ejb.fin;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ITMDBAccessLocal;
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 java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Stateless;

@Stateless
public class StockValAdjTranConf extends ActionHandlerEJB implements StockValAdjTranConfLocal,StockValAdjTranConfRemote {

	
	public String confirm(String tranId, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("--------------confirm method of StockValAdjTranConf1212------------- : "+tranId);
		String retString = "";		
		try
		{
						
				retString = confirmTran(tranId,xtraParams,forcedFlag);
				System.out.println("retString >>>>"+retString);
			
		}
		catch(Exception e)
		{
			System.out.println("Exception :StockValAdjTranConf :confirm():" + e.getMessage() + ":");
			retString = GenericUtility.getInstance().createErrorString(e);
			e.printStackTrace();
		}
		
		return retString;
	}
	private String confirmTran(String tranId,String xtraParams,String forcedFlag) throws ITMException
	{
		System.out.println("---------Class : StockValAdjTranConf-->> confirm method called-----------");   
	    InvAcct inv = new InvAcct();
		ResultSet rs=null;
		Connection conn=null;
		String confirmed = "";
		String isError = "";
		String errCall="";
		PreparedStatement pstmt=null;
		String errString="",sql="",loginEmpCode="",siteCode="",itemCode="",locCode="",lotNo="",lotSl="",lineNo="";
		double PriceListRate=0,amount=0,rateOld=0;
		ConnDriver ConnDriver = new ConnDriver();
		Map <String,String>updateStockMap =new HashMap<String,String>();
		
		int updCnt=0,count=0;
		ITMDBAccessLocal itmdbAccess=new ITMDBAccessEJB();
		try
		{
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			loginEmpCode=GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			loginEmpCode=loginEmpCode==null ? "" :loginEmpCode.trim();
			System.out.println("loginEmpCode---->>["+loginEmpCode+"]");
			conn.setAutoCommit(false);
			sql = "select confirmed from stock_val_adj WHERE tran_id = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if( rs.next())
			{
				confirmed =rs.getString(1) == null ? "N":rs.getString(1);
				
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			
			if( confirmed != null && confirmed.equalsIgnoreCase("Y") )
			{
				
				System.out.println("transaction is already confirmmmm");
				//if already confirm then show error
				errString = itmdbAccess.getErrorString("", "VTALCONF", "", "", conn);
				return errString;
			}
			
			
		  //VTCONSUCC
			tranId=tranId==null ? "" :tranId.trim();
			sql="select h.site_code,d.rate,d.item_code,d.loc_code,d.lot_no,d.lot_sl,d.line_no,d.rate__old "
					+ "from stock_val_adj h,stock_val_adj_det d where h.tran_id=d.tran_id and d.tran_id = ?";
			 pstmt=conn.prepareStatement(sql);
			 pstmt.setString(1, tranId);
			  rs=pstmt.executeQuery();
			  while(rs.next()){
				  System.out.println(">>>>>>> in while loop");
				  siteCode=checkNull(rs.getString(1));				  
				  PriceListRate=rs.getDouble(2);
				  itemCode=checkNull(rs.getString(3));
				  locCode=checkNull(rs.getString(4));
				  lotNo=rs.getString(5);
				  lotSl=rs.getString(6);
				  lineNo=checkNull(rs.getString(7));
				  rateOld=rs.getDouble(8);
				  
				  updateStockMap.put("price_list_rate",Double.toString(PriceListRate));
				  updateStockMap.put("item_code",itemCode);
				  updateStockMap.put("site_code",siteCode);
				  updateStockMap.put("loc_code",locCode);
				  updateStockMap.put("lot_no",lotNo);
				  updateStockMap.put("lot_sl",lotSl);
				  updateStockMap.put("rate__old",Double.toString(rateOld));
				  
				  
				  errCall = inv.stkAdjust(tranId,lineNo,conn);
				  System.out.println(">>>>>>> errCall"+errCall);
				  
				  if(errCall.trim().length() > 0)
				  {
					  System.out.println(">>>>>> isErrorcall");
					  errString = errCall;
					  return errString;  
					 
				  }
				  
				  count=updateStockValAdj(conn, loginEmpCode, tranId);
				  System.out.println("updateStockRateAsPerPriceListRate count-->["+count+"]");
				  if(count > 0){
					
					  count=updateStockRateAsPerPriceListRate(conn, updateStockMap);
					 
					  System.out.println("updateStockValAdj-->>["+count+"]");
					  
						  //confirmed messages show.............
						  System.out.println("COMMITING RECORD");
						  
						  errString = itmdbAccess.getErrorString("", "STKVACONF", "", "", conn);
							//return errString;
							
					  
				  }else{
					//disply error message.
					  conn.rollback();
					  errString = itmdbAccess.getErrorString("", "STKVNCONF", "", "", conn);
						//return errString;
					  
				  }
				  
					
			  }
			  
			  //Changes by Dadaso pawar on 18-04-14- START
			  if(rs!=null){
				  rs.close();
				  rs=null;
			  }
			  if(pstmt!=null){
				  pstmt.close();
				  pstmt=null;
			  }
			//Changes by Dadaso pawar on 18-04-14- END
			 
			  conn.commit();
			  
			  return errString;
			
		
		
		
		
		
		
		}catch(SQLException se)
		{

			System.out.println("SQLException : class StockValAdjTranConf : ");
			se.printStackTrace();
			try
			{
			  conn.rollback();
			  
			    errString = itmdbAccess.getErrorString("", "STKVNCONF", "", "", conn);
				return errString;
			}
			catch(Exception e){
				System.out.println("Exception : Occure during rollback........");e.printStackTrace();
				}
		
		}
		catch(Exception e)
		{
			try
			{
				conn.rollback();
				errString = itmdbAccess.getErrorString("", "STKVNCONF", "", "", conn);
				return errString;
			}
			catch (Exception e1)
			{
			}
			e.printStackTrace();
			System.out.println("Exception Class [StockValAdjTranConf]::"+e.getMessage());
			
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;					
				}	
				if (conn!=null)
				{
					conn.close();
					conn=null;
				}
							
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage());
				e.printStackTrace();
				
			}
		}
		System.out.println("[StockValAdjTranConf]errstring :"+errString);
		return errString;
	}
	
public int updateStockRateAsPerPriceListRate(Connection conn,Map<String,String> updateStockMap){
    PreparedStatement pstmt=null;
    String sql="";
    double rate = 0,oldRate=0;
    rate = Double.parseDouble(updateStockMap.get("price_list_rate"));
    oldRate = Double.parseDouble(updateStockMap.get("rate__old"));
    System.out.println("rate++oldRate>>>"+rate+">>>"+oldRate);
    int count=0;
    if(rate != oldRate){
    
    try{
            sql="update stock set rate = ? where item_code= ? and site_code = ? and loc_code = ? "
                            + "and lot_no = ? and lot_sl = ?";

            pstmt=conn.prepareStatement(sql);
            pstmt.setDouble(1,Double.parseDouble(updateStockMap.get("price_list_rate")));
            pstmt.setString(2,updateStockMap.get("item_code"));
            pstmt.setString(3,updateStockMap.get("site_code"));
            pstmt.setString(4,updateStockMap.get("loc_code"));
            pstmt.setString(5,updateStockMap.get("lot_no"));
            pstmt.setString(6,updateStockMap.get("lot_sl"));

             count=pstmt.executeUpdate();
            
    }
    catch(Exception e){
            System.out.println("Exception in updateStockRateAsPerPriceListRate----------");
                e.printStackTrace();
        }
    }
        return count;
    
}

private int updateStockValAdj(Connection conn,String loginEmpCodeL,String tranId){
	PreparedStatement pstmt=null;
	String sql="";
	int updCnt=0;
	try{
		sql="update stock_val_adj set confirmed = ?,conf_date = ?, emp_code__aprv = ? where tran_id = ?";
		pstmt=conn.prepareStatement(sql);
		pstmt.setString(1, "Y");
		pstmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));
		pstmt.setString(3,loginEmpCodeL);		
		pstmt.setString(4, tranId);
		
		updCnt=pstmt.executeUpdate();
		System.out.println("updateStockValAdj----->>["+updCnt+"]");
		return updCnt;
		

	}
	catch(Exception e){
		e.printStackTrace();
		return -1;
	}
}
private String checkNull(String input){
	if(input==null)
		return "";
	return input.trim();
}
	
}
