package ibase.webitm.ejb.dis;

import java.rmi.RemoteException;
import ibase.webitm.utility.GenericUtility;
import java.sql.*;
import javax.ejb.*;
import ibase.webitm.ejb.*;
import org.w3c.dom.*;
import ibase.webitm.ejb.*;
import ibase.utility.CommonConstants;
import java.util.*;
import java.text.SimpleDateFormat;
import ibase.webitm.utility.*;
//import ibase.webitm.ejb.MasterStateful;
//import ibase.webitm.ejb.MasterStatefulHome;
import ibase.system.config.ConnDriver;
import java.text.DecimalFormat;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class PriceListPos extends ValidatorEJB implements PriceListPosLocal, PriceListPosRemote  //added for ejb3
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	DecimalFormat df = new DecimalFormat( "##.00" );
	
    public String postSaveRec() throws RemoteException,ITMException
	{
		return "";
	} 
    public String postSaveRec(String xmlString1,String domId,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		String returnVal = "";
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				returnVal = generatePriceList( xmlString1, xtraParams, conn );
			}		
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return returnVal;
	}
	private String generatePriceList( String xmlData, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		String retString = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		Document dom = null;
		String childNodeName = null;
		Node childNode = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		int childNodeListLength;
		PreparedStatement pstmt = null;
		PreparedStatement dtlpstmt = null;
		PreparedStatement insPriceListPStmt = null;
		PreparedStatement upDtPlPStmt = null;
		PreparedStatement chkPlpstmt = null;
		PreparedStatement dateOverpstmt = null;
		int ctr = 0;
		String sql = "";
		ResultSet rs = null;
		ResultSet dtlrs = null;
		ResultSet chkPlrs = null;
		String userId ="";
		String termId ="";
		String update_flag = null;
		userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		termId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
		String insPriceList = "INSERT into pricelist(  PRICE_LIST, ITEM_CODE, UNIT, LIST_TYPE, SLAB_NO, "                
					+"	EFF_FROM, VALID_UPTO, LOT_NO__FROM, LOT_NO__TO, "
					+" MIN_QTY, MAX_QTY, RATE, RATE_TYPE, MIN_RATE, "               
					+" CHG_DATE, CHG_USER, CHG_TERM, MAX_RATE, ORDER_TYPE, "             
					+" PRICE_LIST__PARENT, CHG_REF_NO, CALC_BASIS, REF_NO, REF_NO_OLD) "
					+" values ( ?, ?, ?, ?, ?, "
					+"			?, ?, ?, ?, ?, "
					+"			?, ?, ?, ?, ?, "
					+"			?, ?, ?, ?, ?, "
					+"			?, ?, ?, ? ) ";
		
		try
		{
			System.out.println("Post Save EJB calied....");
			System.out.println("Term Id is==>...."+termId);
			conn.setAutoCommit(false);
			dom = genericUtility.parseString( xmlData );
			parentNodeList = dom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for(ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				if ( childNodeName.equalsIgnoreCase( "attribute" ) )
				{
					update_flag = childNode.getAttributes().getNamedItem("updateFlag").getNodeValue();
				}
			}
			
			if( update_flag.equals("A") )
			{
				String pricelistMrp = genericUtility.getColumnValue( "price_list", dom );
				String pricelistItemCode = genericUtility.getColumnValue( "item_code", dom );
				String pricelistSlabNo = genericUtility.getColumnValue( "slab_no", dom );
				String pricelistUnit = genericUtility.getColumnValue( "unit", dom );
				String pricelistListype = genericUtility.getColumnValue( "list_type", dom );
				String pricelistEffRom = genericUtility.getColumnValue( "eff_from", dom );
				String pricelistValidUpto = genericUtility.getColumnValue( "valid_upto", dom );
				String pricelistLotNoF = genericUtility.getColumnValue( "lot_no__from", dom );
				String pricelistLotNoTo = genericUtility.getColumnValue( "lot_no__to", dom );
				String pricelistMinQty = genericUtility.getColumnValue( "min_qty", dom );
				String pricelistMaxQty = genericUtility.getColumnValue( "max_qty", dom );
				String pricelistRateype = genericUtility.getColumnValue( "rate_type", dom );
				String pricelistRate = genericUtility.getColumnValue( "rate", dom );
				String pricelistMinRate = genericUtility.getColumnValue( "min_rate", dom );
				String pricelistMaxRate = genericUtility.getColumnValue( "max_rate", dom );
				String pricelistOrderType = genericUtility.getColumnValue( "order_type", dom );
				String pricelistParent = genericUtility.getColumnValue( "price_list__parent", dom );
				String pricelistRefNo = genericUtility.getColumnValue( "ref_no", dom );
				String pricelistCalcBasis = genericUtility.getColumnValue( "calc_basis", dom );
				String pricelistChgRefNo = genericUtility.getColumnValue( "chg_ref_no", dom );
				String pricelistRefNOld = genericUtility.getColumnValue( "ref_no_old", dom );
				String pricelistChgUser = genericUtility.getColumnValue( "chg_user", dom );
				String pricelistChgTerm = genericUtility.getColumnValue( "chg_term", dom );
				
				String pricelstGen = "";
				double pricelstGencst = 0.0;
				double pricelstGenChrgRet = 0.0;
				double pricelstGenChrgBill = 0.0;
				double pricelstGenMargRet = 0.0;
				int updtCnt = 0;
				int plCount = 0;
				boolean flag = true;
				
				
				double minQty = pricelistMinQty == null ? 0.0 : Double.parseDouble(pricelistMinQty);
				double maxQty = pricelistMaxQty == null ? 9999999.0 : Double.parseDouble(pricelistMaxQty);
				double minRate = pricelistMinRate == null ? 0.0 : Double.parseDouble(pricelistMinRate);
				double maxRate = pricelistMaxRate == null ? 0.0 : Double.parseDouble(pricelistMaxRate);
				double pricelistRateDoub = pricelistRate == null ? 0.0 : Double.parseDouble(pricelistRate);
				int slabNo = pricelistSlabNo == null ? 0 : Integer.parseInt(pricelistSlabNo);
				
				java.sql.Timestamp effFrom = Timestamp.valueOf(genericUtility.getValidDateString(pricelistEffRom, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
				java.sql.Timestamp validUpto = Timestamp.valueOf(genericUtility.getValidDateString(pricelistValidUpto, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");
				
				sql = "SELECT tran_id, price_list "
					 +" FROM pricelist_gen_hdr "
					 +" WHERE price_list__mrp = ? ";
			
				System.out.println( "Select Sql :: " + sql );
				pstmt = conn.prepareStatement( sql );
				pstmt.setString( 1, pricelistMrp );
				
				System.out.println( "Select Sql :: " + sql );
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					String hdrTranId = rs.getString("tran_id");
					pricelstGen = rs.getString("price_list");
					
					sql = "SELECT cst_chrg, vat_chrg__retailer, "
					     +" vat_chrg_billing, margin_retailer "
					     +" FROM pricelist_gen_det where tran_id = ? ";
						 
					System.out.println( "Select Sql :: " + sql );
					dtlpstmt = conn.prepareStatement( sql );
					dtlpstmt.setString( 1, hdrTranId );
					System.out.println( "Select Sql :: " + sql );
					dtlrs = dtlpstmt.executeQuery();
					if( dtlrs.next() )
					{
						pricelstGencst = dtlrs.getDouble("cst_chrg");
						pricelstGenChrgRet = dtlrs.getDouble("vat_chrg__retailer");
						pricelstGenChrgBill = dtlrs.getDouble("vat_chrg_billing");
						pricelstGenMargRet = dtlrs.getDouble("margin_retailer");
					}
					dtlpstmt.close();
					dtlpstmt = null;
				
					double rate = calculateRate( pricelistRateDoub, pricelstGencst, pricelstGenChrgRet, pricelstGenChrgBill, pricelstGenMargRet );
					
					sql = "SELECT count( 1 ) from pricelist where "
			            +" PRICE_LIST = ? "
						+" AND ITEM_CODE = ? "
	                  //  +" AND LIST_TYPE = ? "
						+" AND ( ? between EFF_FROM AND VALID_UPTO) ";
					chkPlpstmt = conn.prepareStatement( sql );
					chkPlpstmt.setString( 1, pricelstGen.trim() );
					chkPlpstmt.setString( 2, pricelistItemCode.trim() );
					//chkPlpstmt.setString( 3, pricelistListype.trim() );
					chkPlpstmt.setTimestamp (3, effFrom );
					
					chkPlrs = chkPlpstmt.executeQuery();
					if(chkPlrs.next())
					{
						plCount = chkPlrs.getInt( 1 );
					}
					chkPlrs.close();
					chkPlrs = null;
					
					if(plCount > 0)
					{
						sql = "update pricelist set "
					     +" valid_upto = ? "
						 +" where price_list = ? "
						 +" AND item_code = ? "
						 //+" AND LIST_TYPE = ?"
						 +" AND ( ? between EFF_FROM AND VALID_UPTO) ";
						 
						 dateOverpstmt = conn.prepareStatement( sql );
					
						String effFromAppl = genericUtility.getValidDateString(effFrom.toString(), genericUtility.getDBDateFormat(), genericUtility.getApplDateFormat());
						Calendar calender = Calendar.getInstance();
						java.text.SimpleDateFormat sdtf = new java.text.SimpleDateFormat( genericUtility.getApplDateFormat() );
						java.util.Date effFromCal = sdtf.parse( effFromAppl );
						calender.setTime( effFromCal );
						calender.add( calender.DATE, -1 );
						java.text.SimpleDateFormat  sdf =  new java.text.SimpleDateFormat( genericUtility.getDBDateFormat() );
						java.sql.Date effectFrom = java.sql.Date.valueOf( sdf.format( calender.getTime() ) );
						Timestamp effectFromTS = Timestamp.valueOf(genericUtility.getValidDateString(effectFrom.toString(), genericUtility.getDBDateFormat(), genericUtility.getDBDateFormat()) + " 00:00:00.0");					
						
						dateOverpstmt.setTimestamp (1, effectFromTS );
						dateOverpstmt.setString( 2, pricelstGen );
						dateOverpstmt.setString( 3, pricelistItemCode );
						//dateOverpstmt.setString( 4, pricelistListype );
						dateOverpstmt.setTimestamp (4, effFrom );
						
						updtCnt = dateOverpstmt.executeUpdate();
					
						dateOverpstmt.close();
						dateOverpstmt = null;
						
						sql = "update pricelist set "
					     +" valid_upto = ? "
						 +" where price_list = ? "
						 +" AND item_code = ? "
						 +" AND ( ? between EFF_FROM AND VALID_UPTO) "
						 +" AND slab_no <> ? ";
						
						dateOverpstmt = conn.prepareStatement( sql );
						 
						dateOverpstmt.setTimestamp (1, effectFromTS );
						dateOverpstmt.setString( 2, pricelistMrp );
						dateOverpstmt.setString( 3, pricelistItemCode );
						//dateOverpstmt.setString( 4, pricelistListype );
						dateOverpstmt.setTimestamp (4, effFrom );
						dateOverpstmt.setInt (5, slabNo );
						
						updtCnt = dateOverpstmt.executeUpdate();
					}
					
					int slabNoUpdt = 1;
					String calcSlab = "SELECT max(SLAB_NO)+1 from PRICELIST where "
									 +" PRICE_LIST = ? "
									 +" AND ITEM_CODE = ? ";
									 //+" AND LIST_TYPE = ? ";
					chkPlpstmt = conn.prepareStatement( calcSlab );
					chkPlpstmt.setString( 1, pricelstGen);
					chkPlpstmt.setString(2, pricelistItemCode);
					
					chkPlrs = chkPlpstmt.executeQuery();
					if(chkPlrs.next())
					{
						slabNoUpdt = chkPlrs.getInt( 1 );
					}
					if( slabNoUpdt == 0 )
					{
						slabNoUpdt = 1;
					}
					
					chkPlrs.close();
					chkPlpstmt.close();
					chkPlrs = null;
					chkPlpstmt = null;
					
					insPriceListPStmt = conn.prepareStatement( insPriceList );
					System.out.println( "Select Sql :: " + insPriceListPStmt );
					
					insPriceListPStmt.setString(1, pricelstGen.trim());
					insPriceListPStmt.setString(2, pricelistItemCode.trim());
					insPriceListPStmt.setString(3, pricelistUnit.trim());
					insPriceListPStmt.setString(4, pricelistListype.trim());
					insPriceListPStmt.setInt(5,  slabNoUpdt);
					insPriceListPStmt.setTimestamp(6, effFrom);
					insPriceListPStmt.setTimestamp(7, validUpto);
					insPriceListPStmt.setString(8, pricelistLotNoF != null ? pricelistLotNoF.trim() : "");
					insPriceListPStmt.setString(9, pricelistLotNoTo != null ? pricelistLotNoTo.trim() : "");
					insPriceListPStmt.setDouble(10, minQty);
					insPriceListPStmt.setDouble(11, maxQty);
					insPriceListPStmt.setDouble(12, rate);
					insPriceListPStmt.setString(13, pricelistRateype != null ? pricelistRateype.trim() : "");
					insPriceListPStmt.setDouble(14, minRate);
					insPriceListPStmt.setTimestamp(15,getCurrdateAppFormat() );
					insPriceListPStmt.setString(16, userId != null ? userId.trim() : "");
					insPriceListPStmt.setString(17, termId != null ? termId.trim() : "");
					insPriceListPStmt.setDouble(18, maxRate);
					insPriceListPStmt.setString(19, pricelistOrderType != null ? pricelistOrderType.trim() : "");
					insPriceListPStmt.setString(20, pricelistParent != null ? pricelistParent.trim() : "");
					insPriceListPStmt.setString(21, pricelistChgRefNo != null ? pricelistChgRefNo.trim() : "");
					insPriceListPStmt.setString(22, pricelistCalcBasis != null ? pricelistCalcBasis.trim() : "");
					insPriceListPStmt.setString(23, pricelistRefNo != null ? pricelistRefNo.trim() : "");
					insPriceListPStmt.setString(24, pricelistRefNOld != null ? pricelistRefNOld.trim() : "");
					
					updtCnt = insPriceListPStmt.executeUpdate();
					flag = false;
					insPriceListPStmt.close();
					insPriceListPStmt = null;
					
					/* String upDtPl = "Update pricelist set eff_from = ?, valid_upto = ? where price_list = ? ";
					upDtPlPStmt = conn.prepareStatement( upDtPl );
					upDtPlPStmt.setTimestamp( 1,effFrom );
					upDtPlPStmt.setTimestamp( 2,validUpto );
					upDtPlPStmt.setString( 3, pricelstGen );
					int updt = upDtPlPStmt.executeUpdate();
					upDtPlPStmt.close();
					upDtPlPStmt = null; */
					retString = "VTSUCCSS";
				}
				pstmt.close();
				pstmt = null;
			}
		}
		catch (Exception e)
		{
			try
			{
				conn.rollback();
				e.printStackTrace();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if ( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if ( insPriceListPStmt != null)
				{
					insPriceListPStmt.close();
					insPriceListPStmt = null;
				}
				if(retString.equals("VTSUCCSS"))
				{
					retString = itmDBAccessEJB.getErrorString("",retString,userId);
					conn.commit();
				}
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}
		}
		//return retString;
		return "";
	}
	
	public double  calculateRate( double rate,double cstChrg, double vatChrgRetailer, double vatChrgBilling, double marginRetailer )
	{
		double disneyBasicPrice = 0.0;
		double totBasicPriceWithVatDisInv = 0.0;
		double vatNotional = 0.0;
		double finalRate = 0.0;
		
		try
		{
			//Calculation by skale start
			
			double vatDisBillg = vatChrgBilling;
			double cstDisBillg = cstChrg;
			double mrpRate = rate;
			double basicMargin = marginRetailer;
			double retBasicMargin = ( mrpRate * ( basicMargin / 100) );
			double mrpRetailerMargin = mrpRate - retBasicMargin ;
			double vatRetailerBillg = vatChrgRetailer;
			
			if( vatDisBillg != 0)
			{
				totBasicPriceWithVatDisInv = mrpRetailerMargin ;
				double vatChargedByDis = totBasicPriceWithVatDisInv * ((vatDisBillg / 100) / ( 1 + ( vatDisBillg / 100 ) ));
				disneyBasicPrice = totBasicPriceWithVatDisInv - vatChargedByDis ;
			}
			else
			{
				vatNotional = mrpRetailerMargin * ( (vatRetailerBillg/100) / ( 1 + (vatRetailerBillg/100) ));
				double cstChargedByDis = ( mrpRetailerMargin - vatNotional ) * ( (cstDisBillg/100) / ( 1 + (cstDisBillg/100) ));
				disneyBasicPrice = mrpRetailerMargin - cstChargedByDis - vatNotional ;
				totBasicPriceWithVatDisInv = disneyBasicPrice + cstChargedByDis;
			}
			finalRate = Double.parseDouble(df.format(disneyBasicPrice));
			//Calculation by skale end
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return finalRate;
	}
	private Timestamp getCurrdateAppFormat()
    {
        String s = "";	
		 Timestamp timestamp = null;		
        GenericUtility genericUtility = GenericUtility.getInstance();
        try
        {
            java.util.Date date = null;
            timestamp = new Timestamp(System.currentTimeMillis());
            
            SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
            date = simpledateformat.parse(timestamp.toString());
            timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
		}
        catch(Exception exception)
        {
            System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
        }
        return timestamp;
    }
}
