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 ibase.webitm.utility.TransIDGenerator;//TID
import ibase.utility.CommonConstants;//TID
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class TaxSchIc extends ValidatorEJB implements TaxSchIcLocal, TaxSchIcRemote
{
	java.sql.Connection conn=null;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccess = new ITMDBAccessEJB();

	/*public void Create() throws RemoteException, CreateException
	{
		System.out.println("TaxSchIc is in Process.ejb..ejb..ejb..ejb..ejb.");
	}
	public void Remove()
	{
	}
	public void Activate()
	{
	}
	public void Passivate()
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

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

//	****************************
	public String validateFilterParams(Document dom, Connection conn)
	{


		System.out.println("Validate the Filter Document in the TaxSchIc.ejb..ejb..ejb..ejb..ejb..ejb..");

		java.sql.PreparedStatement pstmt=null;
		java.sql.ResultSet rs = null;

		String errString = null;
		int count=0;

		String siteCode =null;
		String balgrpTo =null;
		String drcrType =null;
		String adjAmtStr =null;
		String closingBalStr=null;
		String balgrpFr=null;
		String adjAmtstr=null;
		String balgrpadj=null; // added by ihaq
		String sql=null;
		String balgrp =""; //added by rajendra
		double closingBal=0;
		double adjAmt =0;
		StringBuffer sqlStrBuff	=new StringBuffer();
		StringBuffer sqlStrBuff1	=new StringBuffer();



		try
		{
			siteCode = getColumnValue("site_code",dom);
			//commented by rajendra on 26/12/07
			//balgrpTo = getColumnValue("bal_grp__to",dom);
			balgrpFr = getColumnValue("bal_grp__fr",dom);
			//balgrp = getColumnValue("bal_grp",dom);	 //added by rajendra on 26/12/07
			drcrType = getColumnValue("drcr_type",dom);
			adjAmtStr=  getColumnValue("adj_amt",dom);
			balgrpadj=  getColumnValue("bal_group__adj",dom);  //added by ihaq
			closingBalStr =  getColumnValue("closing_bal",dom);

			System.out.println("siteCode:::["+siteCode+"]");
			System.out.println("balgrpFr:::["+balgrpFr+"]");
//			System.out.println("balgrpTo:::["+balgrpTo+"]");
			//System.out.println("balgrp:::["+balgrp+"]");
			System.out.println("drcrType:::["+drcrType+"]");
			System.out.println("adjAmtStr:::["+adjAmtStr+"]");
			System.out.println("closingBalStr:::["+closingBalStr+"]");
			System.out.println("balgrpadj:::["+balgrpadj+"]");  // added by i haq

			StringTokenizer st = new StringTokenizer(balgrpFr,",");
			int cnt=st.countTokens();
			System.out.println("cnt.ejb..ejb..ejb..ejb..ejb..ejb..ejb."+cnt);

			while (st.hasMoreTokens())
			{
				String token=st.nextToken();
				sqlStrBuff.append("'");
				sqlStrBuff.append(token);
				sqlStrBuff.append("'");
				if(cnt != 1)
				{
					sqlStrBuff.append(",");
				}
				System.out.println("token.ejb..ejb..ejb..ejb..ejb..ejb..ejb."+token);
				cnt--;
			 }
			 System.out.println("sqlStrBuff.ejb..ejb..ejb..ejb..ejb..ejb..ejb."+sqlStrBuff);


//COMMENTED BY RAJENDRA ON 27/12/07
//			sql = " select count(1) as count " +
//				  "from tax_balance_grp where " +
//				  " bal_group >= ? and bal_group <= ? and drcr_type <> ?";
			sqlStrBuff1.append( " select count(1) as count from tax_balance_grp where bal_group in ("+sqlStrBuff+") and drcr_type <> ?");
			System.out.println("sqlStrBuff1.ejb..ejb..ejb..ejb..ejb..ejb..ejb."+sqlStrBuff1);
			sql = sqlStrBuff1.toString();

			pstmt = conn.prepareStatement(sql);
//			pstmt.setString(1,balgrpFr);    //COMMENTED BY RAJENDRA ON 27/12/07
//			pstmt.setString(2,balgrpTo);
			pstmt.setString(1,drcrType);

			rs = pstmt.executeQuery();
			if(rs.next())
			{
				count = rs.getInt(1);
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			System.out.println("COUNT:::["+count+"]");
			if(count > 0)
			{
				errString = itmDBAccess.getErrorString("","VTGRPTY","BASE","",conn);
				return errString;
			}


			if (drcrType.equalsIgnoreCase("D"))

			{
			  sql= "select drcr_type from tax_balance_grp where bal_group = ?";

				pstmt = conn.prepareStatement(sql);
		   		pstmt.setString(1,balgrpadj);
				rs = pstmt.executeQuery();
				String balType = null;
				if(rs.next())
				{
					balType = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				System.out.println("BalType:::["+balType+"]");
				if(balType == null || balType.equalsIgnoreCase("D"))
				{
					errString = itmDBAccess.getErrorString("","VTGRPTY","","",conn);
					return errString;
				}
				if(closingBalStr==null)
				{
					closingBalStr="0";
				}
				if(adjAmtStr==null)
				{
					adjAmtStr="0";
				}
				closingBal =  Double.parseDouble(closingBalStr);
				adjAmt =  Double.parseDouble(adjAmtStr);
				if(	adjAmt > closingBal || 	closingBal==0)
				{
					errString = itmDBAccess.getErrorString("","VTTAXADJ1","");
					return errString;
				}
			}

		}

		catch(Exception e)
		{
			e.printStackTrace();
		}
		return errString;
	}

	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
		{
			System.out.println("xmlString:::["+xmlString+"]");
			System.out.println("xmlString:::["+xmlString1+"]");
			System.out.println("xmlString:::["+xmlString2+"]");
			dom = parseString(xmlString);
			System.out.println("xmlString" + xmlString);
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [Gl_open][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
	{
		int n;
		int ctr = 0;
		int currentFormNo = 0;
		String errCode = "";
		java.sql.PreparedStatement pstmt=null;
		java.sql.ResultSet rs = null;
		StringBuffer valueXmlString = new StringBuffer();
		String sql = null;

		String columnValue = "";
		String loginSite = "";

		NodeList parentNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		NodeList childNodeList = null;
		String childNodeName = "";
		Timestamp trandate =null;
		String acctPrd =null;
		String finEnt =null;
		String trandateToTsStr=null;
		String trandateFromTsStr=null;
		double cloBal=0;
		String sCloBal = null;
		String siteCode=null;
		String  trandateTo = null;
		String  trandateFrom = null;
		String drcrType ="";

		String userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		String empCode = getValueFromXTRA_PARAMS(xtraParams,"empCode");
		loginSite = getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");

	//	StringBuffer retString = new StringBuffer();

		try
		{
			conn = getConnection();
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("[TaxSchIc] [itemChanged] :currentFormNo .ejb..ejb.." +currentFormNo);
			System.out.println("Column Name :: " + currentColumn);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			valueXmlString.append("<Detail1>");

			System.out.println("FORM NO:::"+currentFormNo);

			switch (currentFormNo)
			{
				case 1:

					//SEARCHING THE DOM FOR THE INCOMING COLUMN VALUE START
					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));

					if (currentColumn.trim().equals("itm_default"))
					{
						valueXmlString.append("<site_code>").append(loginSite).append("</site_code>\r\n");
						valueXmlString.append("<tran_date__fr>").append(getCurrdateAppFormat()).append("</tran_date__fr>\r\n");
						valueXmlString.append("<tran_date__to>").append(getCurrdateAppFormat()).append("</tran_date__to>\r\n");
						valueXmlString.append("<proc_date>").append(getCurrdateAppFormat()).append("</proc_date>\r\n");
					}
					else if(currentColumn.trim().equalsIgnoreCase("bal_group__adj"))
					{

						trandateTo = getColumnValue("tran_date__to",dom);
						System.out.println("tran_date__to(APPL)::["+trandateTo+"]");

						trandateToTsStr = genericUtility.getValidDateString(trandateTo,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());

						trandate = Timestamp.valueOf(trandateToTsStr+" 00:00:00");
						System.out.println("Tran Date(DB) ::["+trandate+"]");

						siteCode = getColumnValue("site_code",dom);
						System.out.println("SiteCode From Dom ::["+siteCode+"]");


						sql ="select code from acctprd 	where ? between fr_date and to_date";
						System.out.println("bal_group__adj ::["+sql+"]");

						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1,trandate);
						System.out.println("Setting Parameter ::["+trandate+"]");

						rs = pstmt.executeQuery();
						if(rs.next())
						{
							acctPrd = (rs.getString(1)==null?" ":rs.getString(1));
						}
						System.out.println("Account Period::["+acctPrd+"]");

						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						sql ="select fin_entity from site where site_code = '"+siteCode+"'";
							System.out.println("bal_group__adj ::["+sql+"]");
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							finEnt = (rs.getString(1)==null?" ":rs.getString(1));
						}
						System.out.println("Financial Entity::["+finEnt+"]");
						rs.close();
						pstmt.close();
						rs = null;
						pstmt = null;
						System.out.println("Balgroup::["+columnValue+"]");


						sql ="select fn_get_tax_balance('"+acctPrd+"','"+finEnt+"' ,'"+siteCode+"' ,'"+columnValue+"','ZZZZZZ','C' )  - "
					 	+" fn_get_tax_balance('"+acctPrd+"','"+finEnt+"','"+siteCode+"','"+columnValue+"','ZZZZZZ','D' ) as cloBal from dual";
					 	pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							cloBal = rs.getDouble(1);
						}
						System.out.println("Closing Balance::["+cloBal+"]");

						rs.close();
						pstmt.close();
						rs = null;
						pstmt = null;
						// 11/02/2008 manoharan to avoid scientific notation
						sCloBal = decFormat(cloBal);
						//valueXmlString.append("<closing_bal>").append(new Double(cloBal)).append("</closing_bal>\r\n");
						//valueXmlString.append("<adj_amt>").append(new Double(cloBal)).append("</adj_amt>\r\n");
						valueXmlString.append("<closing_bal>").append(sCloBal).append("</closing_bal>\r\n");
						valueXmlString.append("<adj_amt>").append(sCloBal).append("</adj_amt>\r\n");
						// end 11/02/2008 manoharan

					}
					else if(currentColumn.trim().equalsIgnoreCase("tran_date__to"))
					{

						trandateTo = columnValue;
						columnValue = getColumnValue("bal_group__adj",dom);
						System.out.println("tran_date__to(APPL)::["+trandateTo+"]");

						trandateToTsStr = genericUtility.getValidDateString(trandateTo,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());

						trandate = Timestamp.valueOf(trandateToTsStr+" 00:00:00");
						System.out.println("Tran Date(DB) ::["+trandate+"]");

						siteCode = getColumnValue("site_code",dom);
						System.out.println("SiteCode From Dom ::["+siteCode+"]");


						sql ="select code from acctprd 	where ? between fr_date and to_date";
						System.out.println("bal_group__adj ::["+sql+"]");

						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1,trandate);
						System.out.println("Setting Parameter ::["+trandate+"]");

						rs = pstmt.executeQuery();
						if(rs.next())
						{
							acctPrd = (rs.getString(1)==null?" ":rs.getString(1));
						}
						System.out.println("Account Period::["+acctPrd+"]");

						rs.close();
						pstmt.close();
						rs = null;
						pstmt = null;
						sql ="select fin_entity from site where site_code = '"+siteCode+"'";
							System.out.println("bal_group__adj ::["+sql+"]");
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							finEnt = (rs.getString(1)==null?" ":rs.getString(1));
						}
						System.out.println("Financial Entity::["+finEnt+"]");
						rs.close();
						pstmt.close();
						rs = null;
						pstmt = null;

						System.out.println("Balgroup::["+columnValue+"]");

						sql ="select fn_get_tax_balance('"+acctPrd+"','"+finEnt+"' ,'"+siteCode+"' ,'"+columnValue+"','ZZZZZZ','C' )  - "
					 	+" fn_get_tax_balance('"+acctPrd+"','"+finEnt+"','"+siteCode+"','"+columnValue+"','ZZZZZZ','D' ) as cloBal from dual";
					 	System.out.println("sql.ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb..ejb."+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							cloBal = rs.getDouble(1);
						}
						System.out.println("Closing Balance::["+cloBal+"]");

						rs.close();
						pstmt.close();
						rs = null;
						pstmt = null;
						valueXmlString.append("<closing_bal>").append(new Double(cloBal)).append("</closing_bal>\r\n");
						valueXmlString.append("<adj_amt>").append(new Double(cloBal)).append("</adj_amt>\r\n");

					}
					else if (currentColumn.trim().equals("drcr_type"))
					{
						System.out.println("DrCr Type :: " + currentColumn);
						columnValue = getColumnValue("drcr_type",dom);
						System.out.println("DrCr Type value :: " + columnValue);

						if(columnValue.equalsIgnoreCase("C"))
						{
							System.out.println("DrCr Type in if :: " + currentColumn);
							valueXmlString.append("<bal_group__adj protect=\"1\">").append("").append("</bal_group__adj>");
							valueXmlString.append("<adj_amt protect=\"1\">").append(" ").append("</adj_amt>");

							//By ms alam on 19/06/07 for req Id :: DI78SUN046
							//put blank in bal_group__adj & adj_amt in case of drcr_type = credit
							valueXmlString.append("<bal_group__adj>").append(" ").append("</bal_group__adj>\r\n");
							valueXmlString.append("<closing_bal>").append("0").append("</closing_bal>\r\n");

							valueXmlString.append("<adj_amt>").append("").append("</adj_amt>\r\n");
							//ADDED ON 15012007
							valueXmlString.append("<batch_no protect=\"1\">").append(" ").append("</batch_no>\r\n");
						}
						else
						{

							java.sql.Timestamp trandateToTs=null;
							java.sql.Timestamp trandateFromTS=null;
							String batchNoStr=null;
							//String trandateTo =null;
							//String trandateFrom=null;
							//From Filter
							trandateTo = getColumnValue("tran_date__to",dom);
							trandateFrom = getColumnValue("tran_date__from",dom);
							System.out.println("tran_date__to(APPL)::["+trandateTo+"]");
							System.out.println("tran_date__from(APPL)::["+trandateFrom+"]");

							System.out.println("DrCr Type in else :: " + currentColumn);
							//converting to dbdate format
							trandateToTsStr = genericUtility.getValidDateString(trandateTo,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
							trandateFromTsStr = genericUtility.getValidDateString(trandateTo,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
							System.out.println("tran_date__to(DB)::["+trandateToTsStr+"]");
							System.out.println("tran_date__from(DB)::["+trandateFromTsStr+"]");


							//convert timestring to timestamp object
							trandateToTs = Timestamp.valueOf(trandateToTsStr+" 00:00:00");
							trandateFromTS = Timestamp.valueOf(trandateToTsStr+" 00:00:00");
							System.out.println("Tran Date(DB) ::["+trandateToTs+"]");
							System.out.println("Tran Date(DB) ::["+trandateFromTS+"]");

							//calculating the trandate from and to from account perion table

							sql ="select fr_date,to_date from  acctprd 	where ? >= fr_date and ?<=to_date";
							pstmt = conn.prepareStatement(sql);
							pstmt.setTimestamp(1,trandateFromTS);
							pstmt.setTimestamp(2,trandateToTs);

							rs = pstmt.executeQuery();
							System.out.println("Query Executed::::::::::"+sql);
							System.out.println("Setting Parameter ::["+trandateFromTS+"]");
							System.out.println("Setting Parameter ::["+trandateToTs+"]");
							if(rs.next())
							{
								trandateFromTS = rs.getTimestamp(1);;
								trandateToTs = rs.getTimestamp(2);

							}

							System.out.println("trandateFromTS[acctprd]::::::::::"+trandateFromTS);
							System.out.println("trandateToTS[acctprd]::::::::::"+trandateToTs);
							rs.close();
							rs = null;
							//calculating the maximum date from tax_process
							sql ="select max(batch_no) from TAX_PROCESSED where tran_date>=? and tran_date<=? ";
							System.out.println("Debit sql :: " + sql);
							System.out.println("From Date :: " + trandateFromTS);
							System.out.println("From Date :: " + trandateToTs);
							pstmt = conn.prepareStatement(sql);
							pstmt.setTimestamp(1,trandateFromTS);
							pstmt.setTimestamp(2,trandateToTs);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								//Line commented and modified by msalam for Req-Id :: DI78SUN049
								//batchNoStr = (rs.getString(1)==null?" ":rs.getString(1));
								//take data what is coming as it is.
								batchNoStr = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							System.out.println("Query Executed::::::::::"+sql);
							System.out.println("Setting Parameter ::["+trandateFromTS+"]");
							System.out.println("Setting Parameter ::["+trandateToTs+"]");
							System.out.println("batchNoStr::["+batchNoStr+"]");

							valueXmlString.append("<bal_group__adj protect=\"0\">").append(" ").append("</bal_group__adj>\r\n");
							valueXmlString.append("<adj_amt protect=\"0\">").append(" ").append("</adj_amt>\r\n");
							valueXmlString.append("<adj_amt>").append("0.0").append("</adj_amt>\r\n");
							// by msalam on 19/06/07 for req Id :: DI78SUN049
							//If batchNoStr is coming null from database the put blank else put it as it is.
							if(batchNoStr == null || batchNoStr.length() == 0)
								valueXmlString.append("<batch_no protect=\"0\">").append(" ").append("</batch_no>\r\n");
							else
								valueXmlString.append("<batch_no protect=\"0\">").append(batchNoStr).append("</batch_no>\r\n");

						}
					}

				valueXmlString.append("</Detail1>\r\n");
				break;
				case 2:
				valueXmlString.append("</Detail1>");
				break;
			}//END OF SWITCH
			valueXmlString.append("</Root>");
		}//END OF TRY
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
		}
		// 18/01/10 manoharan
		finally {
			try {
			conn.close();
			conn = null;
			}
			catch(Exception fe) {fe.printStackTrace();
			throw new ITMException(fe);
			}
		}
		// end 18/01/10 manoharan
		return valueXmlString.toString();


	}//END OF ITEMCHNGE
	private String getCurrdateAppFormat()
	{
		String currAppdate ="";
		java.sql.Timestamp currDate = null;
		try
		{
			Object date = null;
			currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
			System.out.println(genericUtility.getDBDateFormat());
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = sdf.parse(currDate.toString());
			currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
		}
		catch(Exception e)
		{

		System.out.println("Exception in :::calcFrsBal"+e.getMessage());
		}
		return (currAppdate);
	}
	private String decFormat(double num)
	{
		NumberFormat nf = new DecimalFormat("##############0.000");
		nf.setMaximumFractionDigits(3);
		//nf.setMaximumIntegerDigits(10);
		return nf.format(num);
	}

}