package ibase.webitm.ejb.sys;

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
//Changed by Pawan on 7/2/2011 [SY01SUN042] to import ibase.webitm.ejb.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
//Changed by Pawan on [SY01SUN042] 7/2/2011 to import java.sql.PreparedStatement;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.SQLException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.DOMException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

//Changed by Pawan on 04-02-2011 [SY01SUN042] commented because below imported classes are not being used.start
/* 
import javax.ejb.SessionBean;
import javax.ejb.CreateException;
import javax.ejb.SessionContext;
*/
//Changed by Pawan on 04-02-2011 [SY01SUN042] commented because below imported classes are not being used.end

import java.io.File;
import java.io.FileOutputStream;

//Changed by Pawan 04/02/2011 [SY01SUN042] to migrate from ejb2 to ejb3 Syntax.start
//public class ColumnPropertyEJB implements SessionBean
@javax.ejb.Stateless
public class ColumnProperty extends ValidatorEJB implements ColumnPropertyLocal,ColumnPropertyRemote
//Changed by Pawan 04/02/2011 [SY01SUN042] to migrate from ejb2 to ejb3 Syntax.end
{

	Connection conn = null;
	ConnDriver connDriver = null;
	
	/*
	Changed by Pawan 04/02/2011 [SY01SUN042] .No home interface is there in ejb3 so ejbCreate method is not required
	and callback methods are also required for Stateless component . START
	SessionContext cSessionContext;
	public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called...");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}
	public void setSessionContext(SessionContext mSessionContext) 
	{
		this.cSessionContext = mSessionContext;
	}
	Changed by Pawan 10/5/2010 [SY01SUN042] to migrate from ejb2 to ejb3. END 
	*/
	public String getColumnProperty() throws RemoteException, ITMException
	{
		System.out.println("getColumnProperty Called...");
		return "";
	}
	public String getColumnProperty(String objName, String tomcatPath) throws RemoteException, ITMException
	{
		String selSql = "";
		String winName = "";
		String objType = "";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		String type = "";
		String update = "";
		String key = "";
		String colName = "";
		String dbName = "";
		String dbSize = "";
		String textObjName = "";
		String textName = "";
		String colObjName = "";
		String tabSeq = "";
		String limit = "";
		String nameAttrib = "";
		String typeAttrib = "";
		String labelAttrib = "";
		String sizeAttrib = "";
		String xsdNodeName = "";

		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>");
		StringBuffer textObjXmlStr = null;
		StringBuffer columnObjXmlStr = null;
		
		Document dom = null, textDom = null, columnDom = null;
		NodeList tableColNodeList = null;
		NodeList tableColChildNodeList = null;
		Node tableColChildNode = null;

		NodeList textObjNodeList = null;
		NodeList textObjChildNodeList = null;
		Node textObjChildNode = null;
		Node textObjNode = null;

		NodeList columnObjNodeList = null;
		NodeList columnObjChildNodeList = null;
		Node columnObjNode = null ;
		Node columnObjChildNode = null;
		
		NodeList editStyleNodeList = null;
		Node editStyleNode = null ;
		String editStyleNodeName = null;

		NamedNodeMap typeAttrMap = null;
		String childNodeName = null;
		int i = 0;
		int j = 0;
		int k = 0;
		int l = 0;
		int tc = 0;
		int co = 0;
		int to = 0;

		ArrayList formNoList = new ArrayList();
		File filePtr = null;
		File  xmlFile = null;
		FileOutputStream fos = null;

		try
		{
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");//Gets a Connection
			GenericUtility genericUtility = GenericUtility.getInstance();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			dbf.setIgnoringComments(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			valueXmlString.append("<Root>");
			valueXmlString.append("<Details>");
			
			if (objName.startsWith("w_"))
			{
				winName = objName.toLowerCase();
				objName = objName.substring(2);
			}
			else
			{
				winName = "w_"+objName.toLowerCase();
			}
			filePtr = new File(CommonConstants.JBOSSHOME  + File.separator + "log" + File.separator + "xml" + File.separator + objName + ".xml");

			selSql = "SELECT OBJ_TYPE FROM ITM2MENU WHERE WIN_NAME = '"+winName+"' ";
			System.out.println("selSql :: "+selSql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(selSql);
			if (rs.next())
			{
				objType = rs.getString("OBJ_TYPE");
			}
			else
			{
				valueXmlString.append("</Details>");
				valueXmlString.append("</Root>");
				System.out.println("valueXmlString.toString() :: "+valueXmlString.toString());
				return valueXmlString.toString();
			}
			rs.close();rs = null;
			stmt.close();stmt = null;
			selSql = "SELECT FORM_NO FROM OBJ_FORMS WHERE WIN_NAME = '"+winName+"' ORDER BY FORM_NO ";
			System.out.println("selSql :: "+selSql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(selSql);
			while (rs.next())
			{
				formNoList.add(rs.getString("FORM_NO"));
			}
			rs.close();rs = null;
			stmt.close();stmt = null;
			System.out.println("formNoList :: "+formNoList);
			if ( "R".equals(objType))
			{
				xmlFile = new java.io.File( tomcatPath + "webitm"+File.separator+"reports"+ File.separator + "xsd" + File.separator + objName + ".xsd" );
				System.out.println("xmlFile :: "+xmlFile);
				if (xmlFile != null)
				{
					dom = db.parse(xmlFile);
				}
				else
				{
					valueXmlString.append("</Details>");
					valueXmlString.append("</Root>");
					return valueXmlString.toString();
				}
				valueXmlString.append("<Detail").append("1").append(">");
				NodeList xsdNodeList = null;
				NamedNodeMap xsdAttrMap = null;
				Node xsdNode = null;
				xsdNodeList = dom.getElementsByTagName("argument");
				System.out.println("xsdNodeList.getLength() :: "+xsdNodeList.getLength());
				for(int xd = 0; xd < xsdNodeList.getLength(); xd++)
				{
					//nameAttrib = "";28/11/07
					//typeAttrib = "";28/11/07
					//labelAttrib = "";28/11/07
					//sizeAttrib = "";28/11/07
					//xsdNodeName = "";28/11/07
					xsdNode = xsdNodeList.item(xd);
					xsdNodeName = xsdNode.getNodeName();
					xsdAttrMap = xsdNode.getAttributes();
					if (xsdAttrMap.getNamedItem("visible").getNodeValue().equals("Y"))
					{
						valueXmlString.append("<Column>");
						if( xsdAttrMap.getNamedItem("name") != null)
						{
							nameAttrib = xsdAttrMap.getNamedItem("name").getNodeValue();
						}
						if( xsdAttrMap.getNamedItem("type") != null)
						{
							typeAttrib = xsdAttrMap.getNamedItem("type").getNodeValue();
							typeAttrib = typeAttrib.substring(typeAttrib.lastIndexOf(".")+1, typeAttrib.length());
						}
						if( xsdAttrMap.getNamedItem("label") != null)
						{
							labelAttrib = xsdAttrMap.getNamedItem("label").getNodeValue();
						}
						if( xsdAttrMap.getNamedItem("size") != null)
						{
							sizeAttrib = xsdAttrMap.getNamedItem("size").getNodeValue();
						}
						valueXmlString.append("<display_name>").append(labelAttrib).append("</display_name>");
						valueXmlString.append("<internal_name>").append(nameAttrib).append("</internal_name>");
						valueXmlString.append("<tabsequence>").append("").append("</tabsequence>");
						valueXmlString.append("<limit>").append(sizeAttrib).append("</limit>");
						valueXmlString.append("<db_size>").append(sizeAttrib).append("</db_size>");
						valueXmlString.append("<update>").append("").append("</update>");
						valueXmlString.append("<db_name>").append("").append("</db_name>");
						valueXmlString.append("<type>").append(typeAttrib).append("</type>");
						valueXmlString.append("</Column>");
					}
				}
				valueXmlString.append("</Detail").append("1").append(">");
			}
			else
			{
				//Changed by Pawan on 2/7/2011 [SY01SUN042].
				PreparedStatement pstmt = null;
				String sql = "SELECT PBC_CMNT FROM PBCATCOL WHERE PBC_TNAM = ? AND PBC_OWNR = 'STD' AND PBC_CNAM = ?";
				pstmt = conn.prepareStatement(sql);
				//Changed by Pawan on 2/7/2011 [SY01SUN042].
				for (int m = 0; m < formNoList.size(); m++ )
				{
					xmlFile = null;
					if ( "P".equals(objType))
					{
						xmlFile = new java.io.File( CommonConstants.JBOSSHOME + File.separator + "bin" + File.separator + "metadata" + File.separator + objName + "1" + formNoList.get(m) + ".xml" );
					}
					else
					{
						xmlFile = new java.io.File( CommonConstants.JBOSSHOME + File.separator + "bin" + File.separator + "metadata" + File.separator + objName + "2" + formNoList.get(m) + ".xml" );
					}
					System.out.println("xmlFile :: "+xmlFile);
					if (xmlFile != null)
					{
						dom = db.parse(xmlFile);
					}
					else
					{
						valueXmlString.append("</Details>");
						valueXmlString.append("</Root>");
						return valueXmlString.toString();
					}

					//----------------------------------- Text Object ------------------------------------------------
					textObjXmlStr = null;
					textObjXmlStr = new StringBuffer("<?xml version=\"1.0\"?>");
					textObjXmlStr.append("<Root>");
					textObjXmlStr.append("<TextDetails>");
					textObjNodeList = dom.getElementsByTagName("TextObject");
					for(to = 0; to < textObjNodeList.getLength() ;to++)
					{
						textObjName = "";
						textName = "";
						textObjChildNodeList = textObjNodeList.item(to).getChildNodes();
						for(j = 0 ; j < textObjChildNodeList.getLength() ; j++)
						{
							textObjChildNode = textObjChildNodeList.item(j);
							childNodeName = textObjChildNode.getNodeName();
							if( textObjChildNode.getFirstChild()!= null && textObjChildNode.getFirstChild().getNodeValue() != null)
							{
								if (childNodeName.equals("name"))
								{
									textObjName = textObjChildNode.getFirstChild().getNodeValue();
									textObjName = textObjName.toLowerCase();
								}
								else if (childNodeName.equals("text"))
								{
									textName = textObjChildNode.getFirstChild().getNodeValue();
								}
							}
						}
						textObjXmlStr.append("<").append(textObjName).append(">").append(textName).append("</").append(textObjName).append(">");
					}//End Of Outer For Loop Of Text Object
					textObjXmlStr.append("</TextDetails>");
					textObjXmlStr.append("</Root>");
					textDom = genericUtility.parseString(textObjXmlStr.toString());

					//----------------------------------- Column Object ------------------------------------------------
					columnObjXmlStr = null;
					columnObjXmlStr = new StringBuffer("<?xml version=\"1.0\"?>");
					columnObjXmlStr.append("<Root>");
					columnObjXmlStr.append("<ColumnDetails>");
					columnObjNodeList = dom.getElementsByTagName("ColumnObject");
					for(co = 0; co < columnObjNodeList.getLength() ;co++)
					{
						colObjName = "";
						tabSeq = "";
						columnObjChildNodeList = columnObjNodeList.item(co).getChildNodes();
						for(k = 0 ; k < columnObjChildNodeList.getLength() ; k++)
						{
							columnObjChildNode = columnObjChildNodeList.item(k);
							childNodeName = columnObjChildNode.getNodeName();
							if( columnObjChildNode.getFirstChild()!= null && columnObjChildNode.getFirstChild().getNodeValue() != null)
							{
								if(childNodeName.equals("name"))
								{
									colObjName = columnObjChildNode.getFirstChild().getNodeValue();
									colObjName = colObjName.toLowerCase();
								}
								else if (childNodeName.equals("tabsequence"))
								{
									tabSeq = columnObjChildNode.getFirstChild().getNodeValue();
								}
								else if (childNodeName.equals("EditStyle"))
								{
									editStyleNodeList = columnObjChildNode.getChildNodes();
									for (l = 0; l < editStyleNodeList.getLength(); l++)
									{
										editStyleNode = editStyleNodeList.item(l);
										editStyleNodeName = editStyleNode.getNodeName();
										if (editStyleNode.getFirstChild()!= null && editStyleNode.getFirstChild().getNodeValue()!= null)
										{
											if (editStyleNodeName.equals("limit"))
											{
												limit = editStyleNode.getFirstChild().getNodeValue();
												break;
											}
										}
									}
								}//end Of else if block
							}//End Of If Block
						}//End Of Inner For Loop OF Column Object
						columnObjXmlStr.append("<").append(colObjName).append(">").append(tabSeq).append(":").append(limit).append("</").append(colObjName).append(">");
					}//End Of Outer For Loop Of Column Object
					columnObjXmlStr.append("</ColumnDetails>");
					columnObjXmlStr.append("</Root>");
					columnDom = genericUtility.parseString(columnObjXmlStr.toString());

					//----------------------------------------------------------------------------

					valueXmlString.append("<Detail").append(formNoList.get(m)).append(">");

					//Changed by Pawan on 04-02-2011 [SY01SUN042] to get column description.start
					NodeList tableDefinition = dom.getElementsByTagName( "TableDefinition" );
					String tableName = "";
					if( tableDefinition != null && tableDefinition.getLength() > 0 )
					{
						NodeList childList = tableDefinition.item( 0 ).getChildNodes();	
						int noOfChilds = childList.getLength();
						for (int ctnr = 0; ctnr < noOfChilds; ctnr++)
						{	
							Node childNode = childList.item( ctnr );
							String tableDefChildName = childNode.getNodeName();
							if( tableDefChildName.equalsIgnoreCase("update") )
							{
								if( childNode.getFirstChild()!= null && childNode.getFirstChild().getNodeValue() != null )
								{
									tableName = childNode.getFirstChild().getNodeValue();
								}
							}
						}
					}
					String columnDescr = "";
					
					//Changed by Pawan on 04-02-2011 [SY01SUN042] to get column description.end

					tableColNodeList = dom.getElementsByTagName("table_column");
					for(tc = 0; tc < tableColNodeList.getLength() ;tc++)
					{
						valueXmlString.append("<Column>");
						tableColChildNodeList = tableColNodeList.item(tc).getChildNodes();
						type = "";
						update = "";
						key = "";
						colName = "";
						dbName = "";
						dbSize = "";
						for(i=0 ; i< tableColChildNodeList.getLength() ; i++)
						{
							tableColChildNode = tableColChildNodeList.item(i);
							childNodeName = tableColChildNode.getNodeName();
							if( tableColChildNode.getFirstChild()!= null && tableColChildNode.getFirstChild().getNodeValue() != null)
							{
								if(childNodeName.equals("type"))
								{
									type = tableColChildNode.getFirstChild().getNodeValue();
									type = type.toLowerCase();
									typeAttrMap = tableColChildNode.getAttributes();
									Node attrNameNode = typeAttrMap.getNamedItem("size");	
									if( attrNameNode != null)
									{
										dbSize = attrNameNode.getNodeValue();
									}
								}
								else if (childNodeName.equals("update"))
								{
									update = tableColChildNode.getFirstChild().getNodeValue();
									update = update.toLowerCase();
								}
								else if (childNodeName.equals("name"))
								{
									colName = tableColChildNode.getFirstChild().getNodeValue();
									colName = colName.toLowerCase();
								}
								else if (childNodeName.equals("dbname"))
								{
									dbName = tableColChildNode.getFirstChild().getNodeValue();
									dbName = dbName.toLowerCase();
								}
							}
						}//End OF Inner Loop Of Table Column
						//------------------- Searching for Text Object Starts --------------------------------
						
						// -- 07/02/11
						if ( colName != null && colName.trim().length() > 0 )
						{
							pstmt.setString(1, tableName.toUpperCase());
							pstmt.setString(2, colName.toUpperCase());
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								columnDescr = rs.getString("PBC_CMNT");
							}
							pstmt.clearParameters();
							rs.close();
							rs = null;
						}
						//----07/02/11
						
						textObjNodeList = null;
						textObjNode = null;
						childNodeName = null;

						textObjNodeList = textDom.getElementsByTagName(colName+"_t");
						if (textObjNodeList != null && textObjNodeList.getLength() > 0)
						{
							textObjNode = textObjNodeList.item(0);
							childNodeName = textObjNode.getNodeName();
							if( textObjNode.getFirstChild()!= null && textObjNode.getFirstChild().getNodeValue() != null)
							{
								if (childNodeName.equals(colName+"_t"))
								{
									textName = textObjNode.getFirstChild().getNodeValue();
								}
							}
							valueXmlString.append("<display_name>").append(textName).append("</display_name>");
							valueXmlString.append("<internal_name>").append(colName).append("</internal_name>");
							//Changed by Pawan on 7/2/2011 [SY01SUN042] to set column description.
							valueXmlString.append("<column_descr>").append(checkNull(columnDescr)).append("</column_descr>");
						}
						else
						{
							valueXmlString.append("<display_name>").append("").append("</display_name>");
							valueXmlString.append("<internal_name>").append(colName).append("</internal_name>");
							//Changed by Pawan on 7/2/2011 [SY01SUN042] to set column description.
							valueXmlString.append("<column_descr>").append(checkNull(columnDescr)).append("</column_descr>");
						}
						//----------------------------------- Searching for Column Object Starts -----------------------------
						columnObjNodeList = null;
						columnObjNode = null;
						childNodeName = null;
						String nodeValue = "";

						columnObjNodeList = columnDom.getElementsByTagName(colName);
						if (columnObjNodeList != null && columnObjNodeList.getLength() > 0)
						{
							columnObjNode = columnObjNodeList.item(0);
							childNodeName = columnObjNode.getNodeName();
							if( columnObjNode.getFirstChild()!= null && columnObjNode.getFirstChild().getNodeValue() != null)
							{
								if (childNodeName.equals(colName))
								{
									nodeValue = columnObjNode.getFirstChild().getNodeValue();
									tabSeq = nodeValue.substring(0,nodeValue.indexOf(":"));
									limit = nodeValue.substring(nodeValue.indexOf(":")+1);
								}
							}
							valueXmlString.append("<tabsequence>").append((tabSeq.equals("32766"))?"0":tabSeq).append("</tabsequence>");
							valueXmlString.append("<limit>").append(limit).append("</limit>");
						}
						else
						{
							valueXmlString.append("<tabsequence>").append("").append("</tabsequence>");
							valueXmlString.append("<limit>").append("").append("</limit>");
						}
						valueXmlString.append("<db_size>").append(dbSize).append("</db_size>");
						valueXmlString.append("<update>").append((update == null || update.trim().length() == 0)?"No" :update).append("</update>");
						valueXmlString.append("<db_name>").append(dbName).append("</db_name>");
						valueXmlString.append("<type>").append(type).append("</type>");
						valueXmlString.append("</Column>");
					}//End OF Outer Loop Of Table Column
					valueXmlString.append("</Detail").append(formNoList.get(m)).append(">");
				}//End Of Out For Loop Of formNoList
			}
			valueXmlString.append("</Details>");
			valueXmlString.append("</Root>");
		}
		catch(SQLException se)
		{
			System.out.println("Exception ::"+se);
			se.printStackTrace();
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				//fos = new FileOutputStream(filePtr);
				//fos.write(valueXmlString.toString().getBytes());
				//fos.flush();
				//fos.close();
				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 e)
			{
				System.out.println("Exception in Closing Connection :: " + e);
				throw new ITMException(e);
			}
		}
		return valueXmlString.toString();
	}
	//Changed by Pawan on 7/2/2011 [SY01SUN042] to check null, if null then set empty.start
	private String checkNull(String input)
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}
	//Changed by Pawan on 7/2/2011 [SY01SUN042] to check null, if null then set empty.start
}
