package ibase.webitm.ejb.fin;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;


import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3



@Stateless
public class BudgetGroup extends ValidatorEJB implements BudgetGroupLocal,BudgetGroupRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 
	public String wfValData(String xmlString, String xmlString1, String xmlString2,String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("------------@ wfvalData method called-----------------");
		System.out.println("Xml String : ["+xmlString+"]");
		String errString = null;
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
			
		}
		catch(Exception e)
		{
			System.out.println("Exception : budgetgroup.java : wfValData(String xmlString) : ==>\n"+e.getMessage());
			throw new ITMException(e);
		}
		
		return errString;
	} //end of wfValData 
	
	
	
	public String wfValData(Document dom, Document dom1, Document dom2,String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr=0;
		String childNodeName = null;
		String errString = "";
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		String sql = "";
		int cnt=0;
		int currentFormNo=0;
		int childNodeListLength;
		ConnDriver connDriver = new ConnDriver();
		
		
		String userId="",errCode="";
		
	    String	bud_group_code ="",acct_code="",cctr_code="",anal_code="",descr="",sh_descr =""; 
        try
		   {
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("user ID form XtraParam : "+userId);
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 1 :
				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("bud_group_code"))
					{
						bud_group_code = genericUtility.getColumnValue("bud_group_code",dom);							


						if (bud_group_code == null || bud_group_code.trim().length() == 0 )
						{
						if(!editFlag.equalsIgnoreCase("A"))
						{
								errCode = "VMBDGREM";
								errString = getErrorString("bud_group_code",errCode,userId);
								break;
						}
						}else
						{
							if(!editFlag.equalsIgnoreCase("E"))
							{
							sql = "select count(1) from bud_group where bud_group_code = ? ";
							pstmt=conn.prepareStatement(sql);
							pstmt.setString(1,bud_group_code);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								cnt = rs.getInt(1);
							}
							pstmt.close();
							rs.close();
							pstmt = null;
							rs = null;
							if(cnt == 1)
							{
								errCode = "VMBGCE";
								errString = getErrorString("bud_group_code",errCode,userId);
								break;
							}
						}
						}
 }
					
					if (childNodeName.equalsIgnoreCase("descr"))
					{
						descr = genericUtility.getColumnValue("descr",dom);							


						if (descr == null || descr.trim().length() == 0 )
						{
								errCode = "VEADN3";
								errString = getErrorString("descr",errCode,userId);
								break;
						}
				 }
				
							if (childNodeName.equalsIgnoreCase("sh_descr"))
							{
								sh_descr = genericUtility.getColumnValue("sh_descr",dom);							


								if (sh_descr == null || sh_descr.trim().length() == 0 )
								{
										errCode = "PDESC";
										errString = getErrorString("sh_descr",errCode,userId);
										break;
								}

							
							 }				
					
				 } 
				
				break;
				case 2:
					
					parentNodeList = dom.getElementsByTagName("Detail2");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						System.out.println("value of child node : "+childNode);
						
						
						
						if (childNodeName.equalsIgnoreCase("acct_code"))
						{
							acct_code = genericUtility.getColumnValue("acct_code",dom);							


							if (acct_code == null || acct_code.trim().length() == 0 )
							{
									errCode = "VTINVACCT";
									errString = getErrorString("acct_code",errCode,userId);
									break;
							}
							else
							{
								sql = "select count(1) from accounts where acct_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,acct_code);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								if(cnt == 0)
								{
									errCode = "VMACTCDINV";
									errString = getErrorString("acct_code",errCode,userId);
									break;
								}
							}
							
							//exist validation

					 }
						
						if (childNodeName.equalsIgnoreCase("cctr_code"))
						{
							cctr_code = genericUtility.getColumnValue("cctr_code",dom);							
							

							if (cctr_code != null  && cctr_code.trim().length() > 0 )
							{
								sql = "select count(1) from costctr where cctr_code = ? ";
								pstmt=conn.prepareStatement(sql);
								pstmt.setString(1,cctr_code);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									cnt = rs.getInt(1);
								}
								pstmt.close();
								rs.close();
								pstmt = null;
								rs = null;
								if(cnt == 0)
								{
									errCode = "VTINCCCODE";
									errString = getErrorString("cctr_code",errCode,userId);
									break;
								}
							}

					 }
					
								if (childNodeName.equalsIgnoreCase("anal_code"))
								{
									anal_code = genericUtility.getColumnValue("anal_code",dom);							
									cctr_code = genericUtility.getColumnValue("cctr_code",dom);	

									if (anal_code != null  && anal_code.trim().length() > 0 )
									{											
										sql = "select count(1) from analysis where anal_code = ? ";
										pstmt=conn.prepareStatement(sql);
										pstmt.setString(1,anal_code);
										rs = pstmt.executeQuery();
										if(rs.next())
										{
											cnt = rs.getInt(1);
										}
										pstmt.close();
										rs.close();
										pstmt = null;
										rs = null;
										if(cnt == 0)
										{
											errCode = "VMANAL1";
											errString = getErrorString("anal_code",errCode,userId);
											break;
										}
										if(!editFlag.equals("E"))
					                	{
					                        sql = "select count(1) from bud_group_det where "
					                                  +" cctr_code = ? and anal_code= ? ";
					                        pstmt = conn.prepareStatement(sql);
					                        pstmt.setString(1, cctr_code);
					                        pstmt.setString(2, anal_code);
					                        rs = pstmt.executeQuery();

					                        if (rs.next()) {
					                                cnt = rs.getInt(1);
					                        }
					                        rs.close();
					                        rs = null;
					                        pstmt.close();
					                        pstmt = null;
					                        if (cnt > 0) {
					                        	
					                                errCode = "VMANAL3";
					                                errString = getErrorString("anal_code",errCode, userId);
					                                break;
					                        }
					                }
										
										
									}

								
								 }
							
								if (childNodeName.equalsIgnoreCase("alloc_perc"))
								{
									String alloc_perc = genericUtility.getColumnValue("alloc_perc", dom2);
									if (alloc_perc == null || alloc_perc.trim().length() == 0 )
									{
											errCode = "VMIAPCA";
											errString = getErrorString("alloc_perc",errCode,userId);
											break;
									}
									else
									{
									String score ="";
									Node pNode = null;
									Node cNode = null;
									NodeList cNodeList = null;
									//String alloc_perc = genericUtility.getColumnValue("alloc_perc", dom2);
								   // isActiveStatus = genericUtility.getColumnValue("is_active", dom2); // Added by Amit D on 30 Mar.

								    int alloc_percint = Integer.parseInt(alloc_perc);
								    parentNodeList = dom2.getElementsByTagName("Detail2");
								    int tempscore = 0;
								    System.out.println("total score :" + alloc_percint + " K:parentNodeList.getLength()" + parentNodeList.getLength());
								    for (int k = 0; k < parentNodeList.getLength(); k++)
								    {
									pNode = parentNodeList.item(k);
									cNodeList = pNode.getChildNodes();

									for (int j = 0; j < cNodeList.getLength(); j++)
									{
									    cNode = cNodeList.item(j);
									    childNodeName = cNode.getNodeName();

									   
									     if ("alloc_perc".equals(childNodeName))
									    {
										//added by rajesh on 22-feb-2012
										score = cNode.getFirstChild() == null ? "0" : cNode.getFirstChild().getNodeValue();
										//System.out.println("Update Status INSIDE sCORE ..["+updateStatus+"] ANDF SCORE IS ["+score+"]");

									
										
										tempscore = tempscore + Integer.parseInt(score);
										System.out.println("MY TEMP"+tempscore);
										System.out.println("^^^^^^^ tempscore ..> " + tempscore);
										break;
									    }
									}
									if (tempscore > 100)
									{
										 errCode = "VMAPNMT";
			                                errString = getErrorString("alloc_perc",errCode, userId);
			                                break;
									}
									
									
								    }
								} 
							 }
						 } 
					break;
					default:
					
			} //end switch
		
		} //end try
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString=e.getMessage();
            throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null )
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null )pstmt.close();
					pstmt =null;
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}
		}
		
		System.out.println("ErrString ::[ "+errString+" ]");
		return errString;
	}
	
	
	
	
	public String itemChanged(String xmlString,String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("------------------ itemChanged called------------------");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		try
		{   
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			dom2 = parseString(xmlString2);
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [budgetgroup ][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
	{

		System.out.println("@@@@@@@ itemChanged called");
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		String childNodeName = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		
		int currentFormNo =0;
		String columnValue="",chgTerm="",chgUser="";
		
		int ctr=0;
		
		try
		{		
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext.trim());
			}
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_termr");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "chg_user");
			System.out.println("-------- currentFormNo : "+currentFormNo);
			switch(currentFormNo)
			{
	
				case 1 :
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0; 
				valueXmlString.append("<Detail1>");
				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));
				System.out.println("[" + currentColumn + "] ==> '" + columnValue + "'");
				
			
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )
				{
					System.out.println("------------@@@@@@@@in itm_default@@@@@@@@@---------");
					Calendar currentDate = Calendar.getInstance();
					SimpleDateFormat simpleDateFormatObj = new SimpleDateFormat(genericUtility.getApplDateFormat());
					String systemDate = simpleDateFormatObj.format(currentDate.getTime());
					System.out.println("Now the date is :=>  " + systemDate);
						
					valueXmlString.append("<site_code>").append("").append("</site_code>");
					valueXmlString.append("<chg_date><![CDATA[").append(systemDate).append("]]></chg_date>\r\n");
					valueXmlString.append("<chg_term><![CDATA[").append(chgTerm).append("]]></chg_term>");
					valueXmlString.append("<chg_user><![CDATA[").append(chgUser).append("]]></chg_user>");
					
				}
				valueXmlString.append("</Detail1>");
				}// end switch
			valueXmlString.append("</Root>");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception d)
			{
			  d.printStackTrace();
			}			
		}
		
		return valueXmlString.toString();
	}

}
