package ibase.webitm.ejb.dis;

import java.util.*;
//import java.util.Date;
import java.sql.*;
import java.io.*;
//import org.omg.CORBA.ORB;
import org.w3c.dom.*;
//import java.util.Properties;
import javax.xml.parsers.*;
//import javax.ejb.*;
//import javax.naming.InitialContext;
//import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
//import ibase.webitm.utility.*;
//import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
//import ibase.ejb.*;
import ibase.system.config.*;
//import java.text.SimpleDateFormat;
//import java.util.*;
public class GenVal
{
	Connection conn = null;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	ConnDriver connDriver = new ConnDriver();
	CommonConstants commonConstants = new CommonConstants();
	String errMsg ="";
	public String genVal(String modName ,String objContext,Document data ,Connection conn)
	{
		Statement stmt = null;
		ResultSet rs = null;
		String fldName ="",valType = "",fldMin = "",sqlInput = "",fldMax = "",errCD = "",blankOpt = "",fldData ="";
		String errCode ="";
		String sql = "	SELECT FLD_NAME,VAL_TYPE,FLD_MIN,SQL_INPUT,FLD_MAX,ERROR_CD,BLANK_OPT FROM GENMST WHERE MOD_NAME= '"+modName+"'";
		System.out.println("SQL :: "+sql);
		try
		{
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while (rs.next())
			{
				fldName = rs.getString(1);
				valType = rs.getString(2);
				
				fldMin = rs.getString(3);
				sqlInput = rs.getString(4);
				fldMax = rs.getString(5);
				errCD = rs.getString(6);

				blankOpt = rs.getString(7);

				fldData = getValueFromDom(data,fldName,objContext);
				System.out.println("Fld Name : "+fldName+" Value : "+fldData);
	
				if (checkBlank(fldName,fldData,blankOpt))
				{
					if (valType.equalsIgnoreCase("Q"))
					{
						errMsg = genVal(fldName,modName,data,objContext,fldMin,sqlInput,fldMax,errCD,conn);
					}
					else if(valType.equalsIgnoreCase("S"))
					{
						int fldValue = 0,fldMinValue = 0,fldMaxValue = 0;
						fldValue = Integer.parseInt(fldData);
						fldMinValue = Integer.parseInt(fldMin);
						fldMaxValue = Integer.parseInt(fldMax);
						if (fldValue < fldMinValue || fldValue > fldMaxValue)
						{
							errMsg = errCD;			
						}
					}
				}
				else
				{
					errMsg = errCD;
				}
				if(errMsg.trim().length()>0)
				break;
			}
		}
		catch (SQLException sx)
		{
			System.out.println("SQLException ()::" +sql+ sx.getMessage() + ":");
			sx.printStackTrace();
			
		}
		catch (Exception e)
		{
			System.out.println("Exception () ::" + e.getMessage());
			e.printStackTrace();
			
		}
		return errMsg;

	}

	private boolean checkBlank(String colName, String colValue, String blankOpt)
	{
		boolean result = true;
		try
		{
			System.out.println("Blank Option "+blankOpt);
			if (blankOpt != null && blankOpt.equalsIgnoreCase("Y"))
			{
				if (colValue == null || colValue.trim().length() == 0)
				{
					result = false;
				}
			}
		}catch(Exception e)
		{
			System.out.println("Exception "+e);
		}
		return result;
	}

	public String genVal(String fldName,String modName,Document dom,String objContext,String queryFrDB,String sqlInput,String resultStr,String errcd,Connection conn)
	{
		PreparedStatement pstmt1= null;
		ResultSet rs1  = null;
		java.util.Vector resultStrVec = new java.util.Vector();
		java.util.Vector sqlInputVec = new java.util.Vector();
		java.util.Vector dataVec = new java.util.Vector();
		StringTokenizer st = null;
		//String errcd = "";
		String data="";
		//String queryFrDB ="";
		//String sqlInput = "";
		//String resultStr ="";
		String errCode =" ";
		String colType ="";
		//String sql = "	SELECT FLD_MIN,SQL_INPUT,FLD_MAX, ERROR_CD FROM GENMST WHERE MOD_NAME= '"+modName+"' AND FLD_NAME = '"+fldName+"' AND VAL_TYPE='Q'";
		//**********collecting sql , input string and result string from db for a particular field of a given mode
		try
		{
			//pstmt1 = conn.prepareStatement(sql);
			//rs1=pstmt1.executeQuery();
			/*if (rs1.next())
			{
				queryFrDB = rs1.getString(1);
				sqlInput = rs1.getString(2);
				resultStr = rs1.getString(3);
				errcd =   rs1.getString(4);     */
				System.out.println("Mod Name :::"+modName);
				System.out.println("Field Name :::"+fldName);
				System.out.println("Database queries :::"+queryFrDB);
				System.out.println("Input to query :::"+sqlInput);
				System.out.println("Value after execute :::"+resultStr);
				//***enumerate the sqlinput and store individual parameter in an vector
				//********** check for null
				if(sqlInput != null)
				{
					st = new StringTokenizer(sqlInput,",");
					while (st.hasMoreTokens()) 
					{
						sqlInputVec.add(st.nextToken());
					}
				}
				//***enumerate the resultStr and store individual parameter in an vector
				st = new StringTokenizer(resultStr,",");
				while (st.hasMoreTokens()) 
				{
					resultStrVec.add(st.nextToken());
				}
			/*}
			pstmt1.close();*/
		}
		catch (Exception e)
		{
			System.out.println("Exception (1) ::" + e.getMessage());
			e.printStackTrace();
			
		}
	    try
		{
			//**********executing the query
			StringBuffer QueryBuf= new StringBuffer(queryFrDB);
		    //pstmt1= conn.prepareStatement(queryFrDB);
		    System.out.println("####################Before replace parameter Query :::"+queryFrDB+"\n");
		    System.out.println("Total no of input to query"+queryFrDB+"*********"+sqlInputVec.size());
		    if(sqlInputVec.size() !=0)
		    {
				for(int ctr=0;ctr<sqlInputVec.size();ctr++)
				{
					String colName = (String)sqlInputVec.get(ctr);
					colType = getType(modName,objContext,colName);
					//*****find the value of given field
					String colValue = getValueFromDom(dom,colName,objContext);
					if((colType.toUpperCase().indexOf("STRING") != -1) || (colType.toUpperCase().indexOf("CHAR") != -1) || (colType.toUpperCase().indexOf("VARCHAR") != -1))
					{

					//	System.out.println("SETTING =========================="+ctr); 
					//	System.out.print(colValue + "<==");
					//	pstmt1.setString(ctr+1, colValue); 
						int index = QueryBuf.toString().indexOf('?');
						QueryBuf.replace(index,index+1,"'"+colValue+"'");
					}
					else if((colType.toUpperCase().indexOf("DECIMAL") != -1) || (colType.toUpperCase().indexOf("DOUBLE") != -1) || (colType.toUpperCase().indexOf("NUMBER") != -1) || (colType.toUpperCase().indexOf("LONG") != -1))
					{
						//System.out.print(Double.valueOf(colValue) + "<==");
						//pstmt1.setDouble(ctr+1, Double.valueOf(colValue).doubleValue());
						int index = QueryBuf.toString().indexOf('?');
						QueryBuf.replace(index,index+1,colValue);
						
					}
				/*	else if((colType.toUpperCase().indexOf("DATETIME") != -1) ||  (colType.toUpperCase().indexOf("TIMESTAMP") != -1))
					{
						String dbDateStr =	genericUtility.getValidDateTimeString(colValue, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
						System.out.print("Setting DateTime :["+dbDateStr+"]");
						pstmt1.setTimestamp(ctr+1, java.sql.Timestamp.valueOf(dbDateStr));
						
					}
					else if(colType.toUpperCase().indexOf("DATE") != -1 )
					{
						String dbDateStr =	genericUtility.getValidDateString(colValue,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());
						System.out.print("Setting Date :["+dbDateStr+"]");
						pstmt1.setDate(ctr+1, java.sql.Date.valueOf(dbDateStr));
					}*/
					
				}
			}
		 	System.out.println("####################After replace parameter Query :::"+QueryBuf.toString()+"\n");
			pstmt1= conn.prepareStatement(QueryBuf.toString());
			rs1 = pstmt1.executeQuery();
			ResultSetMetaData rsmd = rs1.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			System.out.println("No Of result "+numberOfColumns);
			System.out.println("No Of result from db "+resultStrVec.size());
			if(numberOfColumns != resultStrVec.size())
			{
				errCode = "CONFIGUREERR"; 
			
			}
			else
			{
					while (rs1.next()) 
					{
						for(int ctr = 1;ctr<=numberOfColumns;ctr++)
						{
							int metaType = rsmd.getColumnType(ctr);
							if (metaType == Types.VARCHAR)
							{
								data = rs1.getString(ctr);
							}
							else if(metaType == Types.NUMERIC)
							{
								data = new Integer(rs1.getInt(ctr)).toString();
							}
							else if(metaType == Types.DECIMAL)
							{
								data = new Double(rs1.getDouble(ctr)).toString();
							}
							else if(metaType == Types.TIMESTAMP)
							{
								data =rs1.getTimestamp(ctr).toString();
							}
						}
						System.out.println("Query RESULT ====>>>"+data);
						dataVec.add(data);
					}
			}
			for(int counter = 0;counter<resultStrVec.size();counter++)
			{
				String result = (String)resultStrVec.get(counter);
				String valueFrDatabase = (String)dataVec.get(counter);
				System.out.println("valueFrDatabase="+valueFrDatabase);
				System.out.println("QRY Result"+result);
				if(!result.trim().equalsIgnoreCase(valueFrDatabase.trim()))
				{
					errCode = errcd ;
					break;
				}
			}
			
		}
		catch (SQLException sx)
		{
			System.out.println("SQLException (2)" +queryFrDB+ sx.getMessage() + ":");
			sx.printStackTrace();
		}
		catch (Exception e)
		{
			System.out.println("Exception (2) ::" + e.getMessage() + ":");
			e.printStackTrace();
		}
		return errCode;
		
	}
	//******** Get the type of the field
	public String getType(String winName,String objContext,String fldName)
	{
		
		Document dom = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String tagName = null;
		String tagValue = null;
		String colName = "";
		String colType = "";
		String childNodeName = ""; 
		String fldType="";
		try
		{
				String ObjName =winName.substring(2,winName.length())+"2"+objContext;
				System.out.println("ObjName :: "+ObjName);
				String filename = CommonConstants.JBOSSHOME + File.separator + "bin\\metadata\\"+ ObjName.trim() + ".xml";
				System.out.println("filename :: "+filename);
				File file = new File(filename);
				DocumentBuilder parser1 = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				dom = parser1.parse(file);
				NodeList columnsNodeList = dom.getElementsByTagName("table_column");
				int tableColLength = columnsNodeList.getLength();
				System.out.println("tableColLength :: "+tableColLength);
				for(int i= 0  ;i < tableColLength;i++ )
				{
					NodeList columnNodeList  =  columnsNodeList.item(i).getChildNodes();
					int tableColChildLength = columnNodeList.getLength();
					for(int j= 0 ;j <  tableColChildLength;j++)
					{	
						Node colNode = columnNodeList.item(j) ; 
						tagName = colNode.getNodeName() ;
					
				
						if (tagName.equals("type") )
						{
							colType = colNode.getFirstChild().getNodeValue();
						}
						if (tagName.equals("name"))
						{
							colName = colNode.getFirstChild().getNodeValue();
						}
					}	
					if(fldName.equalsIgnoreCase(colName))
					{
						fldType = colType;
						System.out.println(colName+"\t"+fldType);
						break;
					}					
				}
		
		}
		catch(FileNotFoundException fileNotFound)
		{
			System.out.println("Exception ::constructor :==>");
			fileNotFound.printStackTrace();
		}
		catch(Exception e )
		{
			e.printStackTrace();
		
		}
		return	fldType;
	}
	//*****Get the parameter field value
	public String getValueFromDom(Document dom,String fldName ,String objContext)
	{
		String value = "";
//		Document dom = null;
		int currentFormNo= 0;
		NodeList parentNodeList = null;
		Node parentNode = null;
		NodeList childNodeList = null;
		int  childNodeListLength = 0;
		Node childNode = null;
		String childNodeName ="";
		
			try
			{
				
				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(int ctr = 0; ctr < childNodeListLength; ctr++)
						{
							childNode = childNodeList.item(ctr);
							childNodeName = childNode.getNodeName();
							if (childNodeName.equals(fldName))
							{
								if (childNode.getFirstChild() != null)
								{
									value = childNode.getFirstChild().getNodeValue();
									break;
								}
								
							}
						}
					
					case 2:
						parentNodeList = dom.getElementsByTagName("Detail2");
						parentNode = parentNodeList.item(0);
						childNodeList = parentNode.getChildNodes();
						childNodeListLength = childNodeList.getLength();
						for(int ctr = 0; ctr < childNodeListLength; ctr++)
						{
							childNode = childNodeList.item(ctr);
							childNodeName = childNode.getNodeName();
							if (childNodeName.equalsIgnoreCase(fldName))
							{
								if (childNode.getFirstChild() != null)
								{
									value = childNode.getFirstChild().getNodeValue();
									break;
								}
							}
								
						}//END FOR
					}//end switch
					//return value;
				}//end try
				catch(Exception e)
				{
					e.printStackTrace();
				}
	return value;
	}
}//END OF EJB

	

