package ibase.webitm.ejb.dis;

import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3


//public class PriceListEJB extends ValidatorEJB implements SessionBean
@Stateless // added for ejb3
public class PriceList extends ValidatorEJB implements PriceListLocal, PriceListRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

	/*public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("Entering into SQLChangeEJB.............");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}


	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		try
		{
			dom = parseString(xmlString); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString :" + xmlString);
			dom1 = parseString(xmlString1); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString1 :" + xmlString1);

			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [PriceListEJB][itemChanged(String,String)] :==>\n"+e.getMessage());
		}
        return valueXmlString;
	}

	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		StringBuffer valueXmlString = new StringBuffer();
		StringBuffer retString = new StringBuffer();
		String errCode = "";
		String sql = "";
		String columnValue = "";
		String childNodeName = "";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		int n = 0;
		int currentFormNo = 0;
		String priceList = null;
		String listType="";
		String itemCode	= null;
		String unit = null;
		String slabno = null;
		String col_name;

		String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		System.out.println("userId ::-"+userId);
		try
		{
			conn = getConnection();
			stmt = conn.createStatement();

			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("[PriceListEJB] [itemChanged] :currentFormNo ....." +currentFormNo);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			valueXmlString.append("<Detail>");
			switch (currentFormNo)
			{
				case 1:
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0;
				int childNodeListLength = childNodeList.getLength();
				do
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equals(currentColumn))
					{
						if (childNode.getFirstChild() != null)
						{
							columnValue=childNode.getFirstChild().getNodeValue().trim();
						}
					}
					ctr++;
				}
				while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
				try
				{

						if (currentColumn.trim().equals("itm_defaultedit"))
						{



							priceList = genericUtility.getColumnValue("price_list",dom) ;
							itemCode = genericUtility.getColumnValue("item_code",dom) ;
							unit = genericUtility.getColumnValue("unit",dom) ;
							listType = genericUtility.getColumnValue("list_type",dom) ;
							slabno = genericUtility.getColumnValue("slab_no",dom) ;

							valueXmlString.append("<price_list protect=\"1\">").append("<![CDATA["+priceList+"]]>").append("</price_list>");
							valueXmlString.append("<item_code protect=\"1\">").append("<![CDATA["+itemCode+"]]>").append("</item_code>");
							valueXmlString.append("<unit protect=\"1\">").append("<![CDATA["+unit+"]]>").append("</unit>");
							valueXmlString.append("<list_type protect=\"1\">").append("<![CDATA["+listType+"]]>").append("</list_type>");
							valueXmlString.append("<slab_no protect=\"1\">").append("<![CDATA["+slabno+"]]>").append("</slab_no>");

							/* sql = "SELECT DISTINCT list_type FROM PRICELIST WHERE  price_list = '"+ priceList +"'";

							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								listType = rs.getString("list_type");
							}
							rs.close();
							rs = null;
							valueXmlString.append("<list_type protect='1\'>").append(listType).append("</list_type>");
							*/
						}
						else
						if (currentColumn.trim().equals("itm_default") )
						{
							long mslab_no=0;
							priceList = genericUtility.getColumnValue("price_list",dom) ;
				            String mprice_list,mitem_code,munit,mlist_type;
							valueXmlString.append("<price_list protect=\"1\">").append("<![CDATA["+priceList+"]]>").append("</price_list>");
							valueXmlString.append("<item_code protect=\"0\">").append("<![CDATA[").append(" ").append("]]>").append("</item_code>");
							valueXmlString.append("<unit protect=\"0\">").append("<![CDATA[ ]]>").append("</unit>");
							// 31/01/2008 manoharan distinct not required
							//sql = "SELECT DISTINCT list_type FROM PRICELIST WHERE  price_list = '"+ priceList +"'";
							sql = "SELECT list_type FROM PRICELIST WHERE  price_list = '"+ priceList +"'";

							rs = stmt.executeQuery(sql);
							System.out.println("SQL....."+sql);
							if (rs.next())
							{
								listType = rs.getString("list_type");
								valueXmlString.append("<list_type protect=\"1\">").append("<![CDATA["+listType+"]]>").append("</list_type>");
							}
							else
							{
								// 31/01/2008 manoharan
								rs.close();
								rs = null;
								sql = "SELECT list_type FROM PRICELIST_MST WHERE  price_list = '"+ priceList +"'";

								rs = stmt.executeQuery(sql);
								System.out.println("SQL....."+sql);
								if (rs.next())
								{
									listType = rs.getString("list_type");
									valueXmlString.append("<list_type protect=\"1\">").append("<![CDATA["+listType+"]]>").append("</list_type>");
								}
								else
								{
									valueXmlString.append("<list_type protect=\"0\">").append("<![CDATA[ ]]>").append("</list_type>");
								}
								// end 31/01/2008 manoharan
							}
							rs.close();
							rs = null;

							sql="SELECT MAX(SLAB_NO) FROM PRICELIST WHERE PRICE_LIST = '" + priceList + "'";

						    rs=stmt.executeQuery(sql);
			                System.out.println("SQL query....."+sql);
							if(rs.next())
							{
								mslab_no=rs.getLong(1);
								valueXmlString.append("<slab_no protect=\"1\">").append(mslab_no + 1).append("</slab_no>");
							}
							else
							{
								valueXmlString.append("<slab_no protect=\"1\">").append("1").append("</slab_no>");
							}
							rs.close();
							rs = null;




							Timestamp mfr_date=null,mto_date=null;
							sql="SELECT FR_DATE,TO_DATE FROM PARAMETER";

							rs=stmt.executeQuery(sql);
							if(rs.next())
							{
								mfr_date=rs.getTimestamp("fr_date")	;
								mto_date=rs.getTimestamp("to_date") ;
							}
							rs.close();
							rs = null;
							//commented by rajendra on 11/10/07 for avoid null
//							mprice_list	= genericUtility.getColumnValue("price_list",dom);
//							mitem_code  = genericUtility.getColumnValue("item_code",dom);
//							munit       = genericUtility.getColumnValue("unit",dom);
//							mlist_type  = genericUtility.getColumnValue("list_type",dom);
//
//							valueXmlString.append("<fr_date>").append(mfr_date).append("</fr_date>");
//							valueXmlString.append("<to_date>").append(mto_date).append("</to_date>");
//							valueXmlString.append("<price_list>").append(mprice_list).append("</price_list>");
//							valueXmlString.append("<item_code>").append(mitem_code).append("</item_code>");
//							valueXmlString.append("<unit>").append(munit).append("</unit>");
//						    valueXmlString.append("<list_type>").append(mlist_type).append("</list_type>");

						}
					else
					if(currentColumn.trim().equals("price_list"))
					{
						String mlist_type="";
						String ls_price_list=genericUtility.getColumnValue("price_list",dom);
						sql="select distinct list_type  from pricelist_mst where  price_list = '"+ls_price_list+"'";

						rs=stmt.executeQuery(sql);
						if(rs.next())
						{
							mlist_type=rs.getString("list_type");
						}
						rs.close();
						rs = null;

						valueXmlString.append("<list_type protect=\"1\">").append("<![CDATA["+mlist_type+"]]>").append("</list_type>");
					}
					else
					if(currentColumn.trim().equals("item_code"))
					{
						String mcode="",mdescr="",munit="",msite_code="";
						mcode=genericUtility.getColumnValue("item_code",dom);
						sql="SELECT DESCR,UNIT ,SITE_CODE FROM ITEM WHERE ITEM_CODE='"+mcode+"'";

						rs = stmt.executeQuery(sql);
						if(rs.next())
						{
							mdescr=rs.getString("descr");
							munit=rs.getString("unit");
							msite_code=rs.getString("site_code");
						}
						rs.close();
						rs = null;

						valueXmlString.append("<item_descr>").append("<![CDATA["+mdescr+"]]>").append("</item_descr>");
						valueXmlString.append("<unit>").append("<![CDATA["+munit+"]]>").append("</unit>");
						valueXmlString.append("<site_code>").append("<![CDATA["+msite_code+"]]>").append("</site_code>");

					}
					else
					if(currentColumn.trim().equals("unit"))
					{
						String mdescr="";
						String munit=genericUtility.getColumnValue("unit",dom)	;
						sql="SELECT DESCR FROM UOM WHERE UNIT='"+munit+"'";

						rs = stmt.executeQuery(sql);
						if(rs.next())
						{
					    	mdescr=rs.getString("descr");
					    }
					    rs.close();
					    rs = null;

					    valueXmlString.append("<descr>").append("<![CDATA["+mdescr+"]]>").append("</descr>");
					}
					else
					if(currentColumn.trim().equals("list_type")	)
					{
						String 	mlist_type="",mrate_type="",mlot_no__from="",mlot_no__to="" ;
						mlist_type=	genericUtility.getColumnValue("list_type",dom);

						if( (mlist_type.equals("M") || mlist_type.equals("N")) )
						{
							mrate_type	  = genericUtility.getColumnValue("rate_type",dom);
							mlot_no__from = genericUtility.getColumnValue("lot_no__from",dom);
							mlot_no__to   = genericUtility.getColumnValue("mlot_no__to",dom);
							valueXmlString.append("<rate_type protect = \"1\">").append("<![CDATA["+mrate_type+"]]>").append("</rate_type>");
							valueXmlString.append("<lot_no__from protect = \"1\">").append("<![CDATA["+mlot_no__from+"]]>").append("</lot_no__from>");
							valueXmlString.append("<lot_no__to protect= \"1\">").append("<![CDATA["+mlot_no__to+"]]>").append("</lot_no__to>");
						}
						else
						{
							valueXmlString.append("<rate_type protect = \"1\">").append("<![CDATA["+mrate_type+"]]>").append("</rate_type>");
							valueXmlString.append("<lot_no__from protect = \"0\">").append("<![CDATA["+mlot_no__from+"]]>").append("</lot_no__from>");
							valueXmlString.append("<lot_no__to protect = \"0\">").append("<![CDATA["+mlot_no__to+"]]>").append("</lot_no__to>");

					    }

					}

				}//try
				catch(Exception e)
				{
				System.out.println("Exception :[PriceListEJB][itemChanged::case 1::order_type] :==>\n"+e.getMessage());
				throw new ITMException(e);
				}
				valueXmlString.append("</Detail>");
				break;
			}//Switch
			valueXmlString.append("</Root>");
		}//try


		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception s){}
		}
		return valueXmlString.toString();
	}//itemChanged()
	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String  errString = null;
		System.out.println("Entering into  validations ...................");
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : PayableOpeningsEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}

	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String errString = "";
		String errCode = "";
		String sql = "";
		String userId = "";
		String custCode = "";
		String empCodeGiven = "";
		String empCodeMerge = "";
		String childNodeName = "";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr,currentFormNo=0;
		int childNodeListLength;
		try
		{
			conn = getConnection();
			stmt = conn.createStatement();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			System.out.println("userId = "+userId);
			System.out.println("xtraParams = "+xtraParams);

			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}

			parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for (ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				switch (currentFormNo)
				{
					case 1:
					{
						if (childNodeName.equals("slab_no"))
						{
					    }

					    else if(childNodeName.equals("tax_base"))
					    {

					    }
					    else if(childNodeName.equals("item_code"))
					    {
	  			            System.out.println("childNodeName 1. : " + childNodeName);
						    String 	mitem_code = genericUtility.getColumnValue("item_code",dom);
						    sql="select count(*) as count from item where item_code = '"+mitem_code+"'";
						    rs=stmt.executeQuery(sql);
							System.out.println("SQL"+sql);
							int cnt=0;
							if(rs.next())
							{
								cnt=rs.getInt("count");
							}
							rs.close();
							rs = null;
							if(cnt==0)
							{
								errCode = "VMITEM_CD";
								errString = getErrorString("min_qty",errCode,userId);
							}
							sql="select active from item where item_code='"+mitem_code+"'";
							String mactive=null;
							rs=stmt.executeQuery(sql);
							if(rs.next())
							{
								mactive=rs.getString("active");
							}
							rs.close();
							rs = null;
						   if(mactive.equals("N"))
						   {
								errCode="VTITEM4";
								errString = getErrorString("min_qty",errCode,userId);
						   }

				   	    }
						else if (childNodeName.equals("price_list__parent"))
						{
							String ls_plist_parent,Is_price_list;
							System.out.println("childNodeName 1. : " + childNodeName);
							ls_plist_parent = genericUtility.getColumnValue("price_list__parent",dom);
							Is_price_list   = genericUtility.getColumnValue("price_list",dom);
							//System.out.println("childNode.getFirstChild() 1. : " + childNode.getFirstChild());
							if (ls_plist_parent == null || ls_plist_parent.trim().length() == 0)
							{
								if(ls_plist_parent.trim().equals(Is_price_list) )

								errCode = "VTPARENTPL";
								errString = getErrorString("price_list__parent",errCode,userId);
								break;
							}
						else if (childNodeName.equals("min_qty"))
						{
							int mmaxqty,mminqty;
							mmaxqty=Integer.parseInt(genericUtility.getColumnValue("min_qty",dom));
							mminqty=Integer.parseInt(genericUtility.getColumnValue("max_qty",dom));


							if (mmaxqty < mminqty )
							{
								errCode = "VMMINQTY";
								errString = getErrorString("min_qty",errCode,userId);
								break;
							}


						}
						else if(childNodeName.equals("valid_upto"))
						{
							Timestamp mvalid_upto,meff_from;
							String strvalid_upto,strmeff_from;
							strvalid_upto=genericUtility.getColumnValue("valid_upto",dom) ;
							strmeff_from=genericUtility.getColumnValue("meff_from",dom);



							 String valid_uptoDate=getValidDateTimeString(strvalid_upto,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat());
							 String eff_fromDate= getValidDateTimeString(strmeff_from,GenericUtility.getInstance().getApplDateFormat(),GenericUtility.getInstance().getDBDateFormat());

							 mvalid_upto = Timestamp.valueOf(valid_uptoDate+" 00:00:00");
							 meff_from = Timestamp.valueOf(eff_fromDate+" 00:00:00");

							if( ( mvalid_upto.compareTo( meff_from) ) ==0 )
							{
								errCode="VMVAL_UPTO";
								errString=getErrorString("valid_upto",errCode,userId);
								break;
							}
						}

						else if(childNodeName.equals("tax_code"))
						{
							String mValue=genericUtility.getColumnValue("tax_code",dom);
							sql="Select Count(*) as count from tax where tax_code = '"+mValue+"'";
							rs=stmt.executeQuery(sql);
							System.out.println("SQL"+sql);
							if(rs.next())
							{
								int cnt=rs.getInt("count");

								if(cnt==0)
								errCode = "VTTAX1";
								break;

							}
							rs.close();
							rs = null;
						}

					else if(childNodeName.equals("rate"))
					{
						int mrate;
						mrate=	Integer.parseInt(genericUtility.getColumnValue("rate",dom) );
						if(mrate<=0)
						errCode="VTRATE2";
						errString=getErrorString("rate",errCode,userId);

					}


					}//case1
					break;
					}
				}//switch
			}//for
		}//try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection.....");
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			}catch(Exception se){}
		}
		System.out.println("ErrString ::"+errString);
		return errString;
	}//wfValData







public String getValidDateTimeString(String dateTimeStr, String sourceDateTimeFormat, String targetDateTimeFormat) throws ITMException
	{
		System.out.println("Getting the valid datetime string for dateTimeStr :"+dateTimeStr+": which is in format :"+sourceDateTimeFormat);
		Object date = null;
		String retDateStr = "";
		try
		{
			if (!(sourceDateTimeFormat.equalsIgnoreCase(targetDateTimeFormat)))
			{
				if (sourceDateTimeFormat.indexOf("/") != -1)
				{
					dateTimeStr.replace('/', '-');
				}
				else if (sourceDateTimeFormat.indexOf(".") != -1)
				{
					dateTimeStr.replace('.', '-');
				}
				date = new SimpleDateFormat(sourceDateTimeFormat).parse(dateTimeStr);
				SimpleDateFormat sdfOutput = new SimpleDateFormat(targetDateTimeFormat);
				retDateStr = sdfOutput.format(date);
			}
			else
			{
				retDateStr = dateTimeStr;
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception :GenericUtility :getValidDateString :==>"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("retDateStr :"+retDateStr);
		return retDateStr;
	}










}//class