package ibase.webitm.ejb.dis;

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

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

import ibase.utility.BaseException;
import ibase.utility.BaseLogger;
import ibase.utility.E12GenericUtility;
import ibase.utility.GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

public class ReqForQuotationIC extends ValidatorEJB {
	E12GenericUtility genericUtility = new E12GenericUtility();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>>ReqForQuotationIC validation called>>>>>>>>>>>>>>>>>>>:::");

		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		BaseLogger.log("3", null, null, "xmlString ReqForQuotationIC [" + xmlString + "]");
		BaseLogger.log("3", null, null, "xmlString1 ReqForQuotationIC [" + xmlString1 + "]");
		BaseLogger.log("3", null, null, "xmlString2 ReqForQuotationIC [" + xmlString2 + "]");
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			BaseLogger.log("3", null, null, "ErrString: " + errString);

		} catch (Exception e) {
			System.out.println("Exception: ReqForQuotationIC: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		BaseLogger.log("3", null, null, "Returning from ReqForQuotationIC wfValData");

		return (errString);
	}
	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, "9>>>>>>>>>>>>>>>>>>ReqForQuotationIC validation called >>>>>>>>>>>>>>>>>>>");
		BaseLogger.log("3", null, null, "Inside ReqForQuotationIC validation");


		GenericUtility genericUtility = GenericUtility.getInstance();
        try {
			BaseLogger.log("3", getUserInfo(), null,  "dom case2*>>>> Elements>>["+genericUtility.serializeDom(dom).toString()+"]");//added for testing
            BaseLogger.log("3", getUserInfo(), null,  "dom2 case2*>>>> Elements>>["+genericUtility.serializeDom(dom2).toString()+"]");//added for testing
			BaseLogger.log("3", getUserInfo(), null,  "dom1 case2*>>>> Elements>>["+genericUtility.serializeDom(dom1).toString()+"]");
		} catch (BaseException e1) {
			e1.printStackTrace();
		}


		String userId = "";

		String requestId = "";
		String sql="";
		String errString = "";

		Connection connection = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;

		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;

		int noOfChilds = 0;
		int currentFormNo = 0;

		try
		{
			SimpleDateFormat DOB = new SimpleDateFormat(getApplDateFormat());
			connection = getConnection(); 

			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch ( currentFormNo )
			{
				case 2:
				{
					parentList = dom.getElementsByTagName("Detail"+ currentFormNo);
					int parentNodeListLength = parentList.getLength();
					System.out.println("parentNodeListLength["+parentNodeListLength+"]");

					for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
					{
						parentNode = parentList.item(prntCtr);
						System.out.println("value of parentNode"+parentNode);
						childList = parentNode.getChildNodes();
						noOfChilds = childList.getLength();
						System.out.println("value of noOfChilds"+noOfChilds);
						for (int ctr = 0; ctr < noOfChilds; ctr++)
						{
							childNode = childList.item(ctr);
							System.out.println("childNode"+childNode);
							if( childNode.getNodeType() != Node.ELEMENT_NODE )
							{
								continue;
							}

							childNodeName = childNode.getNodeName();

							
							if( childNodeName.equalsIgnoreCase("ptr_flag") )
							{
								String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));
								String competitorRate = checkNull(genericUtility.getColumnValue("competitor_rate", dom));
								String competitorItem = checkNull(genericUtility.getColumnValue("competitor_item", dom));
								String competitorName = checkNull(genericUtility.getColumnValue("competitor_name", dom));
								BaseLogger.log("3", null, null, "ReqForQuotationIC ptrFlag wfValData [" + ptrFlag + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorRate wfValData [" + competitorRate + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorItem wfValData [" + competitorItem + "]");
								BaseLogger.log("3", null, null, "ReqForQuotationIC competitorNane wfValData [" + competitorName + "]");


								if (ptrFlag.equalsIgnoreCase("N") || ptrFlag.trim().isEmpty()) {
								    BaseLogger.log("3", null, null, "ReqForQuotationIC in condition ptrFlag wfValData::: [" + ptrFlag + "]");

								    // Check if any of the competitor fields are null or blank
								    if ((competitorRate == null || competitorRate.trim().isEmpty()) 
								            || (competitorItem == null || competitorItem.trim().isEmpty()) 
								            || (competitorName == null || competitorName.trim().isEmpty())) { 
								        BaseLogger.log("3", null, null, "ReqForQuotationIC in competitor details null [" + ptrFlag + "]");
								        errString = getErrorString("ptr_flag", "COMPDETM", userId);
								        BaseLogger.log("3", null, null, "ReqForQuotationIC in competitor details null errString:: [" + errString + "]");
								        break;
								    }
								}

							}
							//End elseif
						}//End for loop
					}//End for loop
					break;
				}//case1
			}//switch
		
		}//try
		catch (Exception e)
		{
			System.out.println ("Exception: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e); 
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(connection != null)
				{
					connection.close();
					connection = null;
				}
            }
			catch(Exception e)
			{
				errString = genericUtility.createErrorString(e);
			}
		}
		return (errString);
	
	}
	
	
	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext,
			String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null,
				">>>>>>>>>>>>>>>>>> ReqForQuotationIC itemchange called Ajit>>>>>>>>>>>>>>>>>>>");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			BaseLogger.log("3", null, null, "xmlString ReqForQuotationIC [" + xmlString + "]");
			BaseLogger.log("3", null, null, "xmlString1 ReqForQuotationIC [" + xmlString1 + "]");
			BaseLogger.log("3", null, null, "xmlString2 ReqForQuotationIC [" + xmlString2 + "]");
			errString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			BaseLogger.log("3", null, null, "ErrString :" + errString);

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Exception :ReqForQuotationIC :itemChanged(String,String):" + e.getMessage() + ":");

			errString = genericUtility.createErrorString(e);
		}
		BaseLogger.log("3", null, null, "returning from ReqForQuotationIC itemChanged");

		return errString;
	}
	
	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", getUserInfo(), null, ">>>>>>>>>>>>>>>>>> ReqForQuotationIC itemchange called Ajit>>>>>>>>>>>>>>>>>>>");
		System.out.println("Inside itemchange");
		Connection con = null;
		PreparedStatement psSiteCustomer = null;
		PreparedStatement psCustomer = null;
		PreparedStatement psPriceList = null;
		PreparedStatement psFinEntity = null;
		String reStr = "";
		ResultSet rs = null;
		StringBuffer valueXmlString = null;
		int currentFormNo = 0;
		String userId = "";
		String sql = "";
		String priceList = "";
		int rate= 0;
		String finEntity = "";
		try {
			 UserInfoBean userInfo = getUserInfo(); 
			 String siteCode = checkNull(userInfo.getSiteCode());
			 String userCode = checkNull(userInfo.getLoginCode());
				BaseLogger.log("3", null, null, "ReqForQuotationIC in siteCodeFromUserInfo:: "+siteCode);
				BaseLogger.log("3", null, null, "ReqForQuotationIC in userCodeFromUserInfo:: "+userCode);

			con = getConnection();
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode"); // To get user details after login
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}

			// start creating xml
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			String ptrFlag = checkNull(genericUtility.getColumnValue("ptr_flag", dom));

			BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition ptrFlag:: "+ptrFlag);

			BaseLogger.log("3", null, null, "ReqForQuotationIC currentFormNo "+currentFormNo);

			
			
			
			switch (currentFormNo) {
				
			case 2:
				
				valueXmlString.append("<Detail2>");
				if ("itm_default".equalsIgnoreCase(currentColumn.trim())) {
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default ");
					//Management rate block[Start]
					String finEntityQuery = "select fin_entity from site where site_code = ?";
					psFinEntity = con.prepareStatement(finEntityQuery);
					psFinEntity.setString(1, siteCode);
					rs = psFinEntity.executeQuery();
					if(rs.next()) {
						finEntity = checkNull(rs.getString("fin_entity"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default finEntity:: "+finEntity);

					rs.close();
					psFinEntity.close();
					
					// Now, use finEntity to fetch VAR_VALUE from finparm
					String varValueQuery = "select VAR_VALUE from finparm where ADDL_VALUE = ?";
					PreparedStatement psVarValue = con.prepareStatement(varValueQuery);
					psVarValue.setString(1, finEntity);
					ResultSet rsVarValue = psVarValue.executeQuery();
					String varValue = null;
					if (rsVarValue.next()) {
					    varValue = checkNull(rsVarValue.getString("VAR_VALUE"));
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default varValue:: " + varValue);

					// Clean up the result set and prepared statement for the varValue query
					rsVarValue.close();
					psVarValue.close();

					// Finally, use varValue to fetch the rate from pricelist
					String rateQuery = "select rate from pricelist where price_list = ?";
					PreparedStatement psRate = con.prepareStatement(rateQuery);
					psRate.setString(1, varValue);
					ResultSet rsRate = psRate.executeQuery();
					int MngmntAprvRate = 0;
					if (rsRate.next()) {
						MngmntAprvRate = rsRate.getInt("rate");
					}
					BaseLogger.log("3", null, null, "ReqForQuotationIC in itm default rate:: " + rate);

					// Clean up the result set and prepared statement for the rate query
					rsRate.close();
					psRate.close();
					
					
					String priceSql =
					        "SELECT fp.VAR_NAME, pl.rate " +
					        "FROM finparm fp " +
					        "JOIN site s ON s.fin_entity = fp.ADDL_VALUE " +
					        "JOIN pricelist pl ON pl.price_list = fp.VAR_VALUE " +
					        "WHERE s.site_code = ? " +
					        "AND fp.VAR_NAME IN ('RFQ_PTS','RFQ_PTD')";


					PreparedStatement psPrice = con.prepareStatement(priceSql);
					psPrice.setString(1, siteCode);

					ResultSet rsPrice = psPrice.executeQuery();

					BigDecimal pts = null;
					BigDecimal ptd = null;
					BigDecimal PriceRate = null;
					while (rsPrice.next()) {
						
					    String varName = checkNull(rsPrice.getString("VAR_NAME"));
					     PriceRate = rsPrice.getBigDecimal("rate");

					    if ("RFQ_PTS".equals(varName)) {
					        pts = PriceRate;
					    } else if ("RFQ_PTD".equals(varName)) {
					        ptd = PriceRate;
					    }
					}

					
					//PTR calculation start
				    String siteCustomerQuery = 
					        "SELECT PRICE_LIST FROM SITE_CUSTOMER " +
					        "WHERE SITE_CODE = ? AND CUST_CODE = ?";

					    psSiteCustomer = con.prepareStatement(siteCustomerQuery);
					    psSiteCustomer.setString(1, siteCode);
					    psSiteCustomer.setString(2, custCode);

					    rs = psSiteCustomer.executeQuery();

					    if (rs.next()) {
					        priceList = rs.getString("PRICE_LIST");
					    }

					    rs.close();
					    psSiteCustomer.close();

					    // Step 2: If not found in SITE_CUSTOMER, fetch from CUSTOMER
					    if (priceList == null || priceList.trim().isEmpty()) {

					        String customerQuery =
					            "SELECT PRICE_LIST FROM CUSTOMER WHERE CUST_CODE = ?";

					        psCustomer = con.prepareStatement(customerQuery);
					        psCustomer.setString(1, custCode);

					        rs = psCustomer.executeQuery();

					        if (rs.next()) {
					            priceList = rs.getString("PRICE_LIST");
					        }

					        rs.close();
					        psCustomer.close();
					    }

					    // Step 3: Fetch RATE from PRICELIST table
					    if (priceList != null && !priceList.trim().isEmpty()) {

					        String priceListQuery =
					            "SELECT RATE FROM PRICELIST WHERE PRICE_LIST = ?";

					        psPriceList = con.prepareStatement(priceListQuery);
					        psPriceList.setString(1, priceList);

					        rs = psPriceList.executeQuery();

					        if (rs.next()) {
					            rate = rs.getInt("RATE");
					        }

					        rs.close();
					        psPriceList.close();
					    }

					//PTR calculation end
					
					valueXmlString.append("<rate_apprv>").append("<![CDATA["+MngmntAprvRate+"]]>").append("</rate_apprv>\r\n");
					valueXmlString.append("<ptd>").append("<![CDATA["+ptd+"]]>").append("</ptd>\r\n");
					valueXmlString.append("<pts>").append("<![CDATA["+pts+"]]>").append("</pts>\r\n");
					valueXmlString.append("<ptr>").append("<![CDATA["+rate+"]]>").append("</ptr>\r\n");

					//Management rate block[End]
				}
				if ("ptr_flag".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flag ");
					String custCode = checkNull(genericUtility.getColumnValue("cust_code", dom1));

					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition:: "+ptrFlag);
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition siteCode:: "+siteCode);
					BaseLogger.log("3", null, null, "ReqForQuotationIC in ptr_flat condition custCode:: "+custCode);

					if(ptrFlag.equalsIgnoreCase("Y")) {
											
						BaseLogger.log("3", getUserInfo(), null, "Final RATE : " + rate);
						valueXmlString.append("<rate_quot protect='1'>").append("<![CDATA["+rate+"]]>").append("</rate_quot>\r\n");

						
					}else if(ptrFlag.equalsIgnoreCase("N")) {
						valueXmlString.append("<rate_quot protect='0'>").append("<![CDATA[]]>").append("</rate_quot>\r\n");
					}
				}
				if ("rate_quot".equalsIgnoreCase(currentColumn.trim())) {
					BaseLogger.log("3", null, null, "ReqForQuotationIC in rate_quot ::");
					String rateQuot = genericUtility.getColumnValue("rate_quot", dom);
					String rateApprv = checkNull(genericUtility.getColumnValue("rate_apprv", dom));
					String ratePtr = checkNull(genericUtility.getColumnValue("ptr", dom));

					BaseLogger.log("3", null, null, "ReqForQuotationIC in rate_quot:: "+rateQuot+" rateApprv::"+rateApprv+ " ratePtr::"+ratePtr);
					

					if (!rateQuot.isEmpty() && !rateApprv.isEmpty()) {
					    BigDecimal rateApprvVal = new BigDecimal(rateApprv);
					    BigDecimal rateQuotVal = new BigDecimal(rateQuot);
					    BigDecimal ratePtrVal = new BigDecimal(ratePtr);

						BaseLogger.log("3", null, null, "ReqForQuotationIC after conversion rateQuotVal:: "+rateQuotVal+" rateApprvVal::"+rateApprvVal);

					    
					    
					    //added condition when ptr and rate_quot is same direct approval without management
						/*
						 * if (ratePtrVal.compareTo(rateQuotVal) == 0) { BaseLogger.log("3", null, null,
						 * "in ratePtrVal == rateQuotVal condition"); String detail1Xml =
						 * "<Detail1><mgmnt_apprv><![CDATA[N]]></mgmnt_apprv><wf_status><![CDATA[A]]></wf_status></Detail1>";
						 * 
						 * int pos = valueXmlString.indexOf("</header>");
						 * 
						 * if (pos != -1) { pos += "</header>".length(); // move after </header>
						 * valueXmlString.insert(pos, detail1Xml); }
						 * 
						 * BaseLogger.log("3", null, null,
						 * "in rateApprvVal greater condition updatedXml ::"+valueXmlString); }
						 */
					    
					    
					    if (rateApprvVal.compareTo(rateQuotVal) > 0) {
					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition");
					        String detail1Xml = "<Detail1><mgmnt_apprv><![CDATA[Y]]></mgmnt_apprv><wf_status><![CDATA[P]]></wf_status></Detail1>";

					        int pos = valueXmlString.indexOf("</header>");

					        if (pos != -1) {
					            pos += "</header>".length();   // move after </header>
					            valueXmlString.insert(pos, detail1Xml);
					        }

					        BaseLogger.log("3", null, null, "in rateApprvVal greater condition updatedXml ::"+valueXmlString);

					        
					    }
					}


				}
				valueXmlString.append("</Detail2>\r\n");
				break;
			}
	        BaseLogger.log("3", null, null, "in rateApprvVal greater condition reStr>>>>> "+reStr);
			valueXmlString.append("</Root>\r\n");
		} catch (Exception e) {
			BaseLogger.log("3", getUserInfo(), null, "Exception :AssetAssign :itemChanged(Document,String):" + e.getMessage() + ":");

			e.printStackTrace();
		} finally {
			closeResources(rs, psSiteCustomer, conn);
			closeResources(rs, psCustomer, conn);
			closeResources(rs, psPriceList, conn);

		}
		BaseLogger.log("3", getUserInfo(), null, "asset_assign valueXmlString::"+valueXmlString.toString());
		return valueXmlString.toString();
	}
	
	private void closeResources(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

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