

/********************************************************
	Title     : RepSpecificAd.java
	Date      : 23-MAR-2015
	Developer : CHETNA SHAHU
********************************************************/

package ibase.webitm.ejb.adm;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@Stateless  

public class RepSpecificAd  extends ValidatorEJB implements RepSpecificAdLocal,RepSpecificAdRemote {
	
	
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		
		System.out.println("In ReportSpecificationMaster[wfValData]");
		
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
			
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("In wfValData Current xmlString="+xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("In wfValData Header xmlString1="+xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
				System.out.println("In wfValData All xmlString2="+xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document curDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
	 	String reportId = "";
		String errorType = "";
		String childNodeName = null;
		String errCode = "";
		String adCode = "";
		String descr = "";
		String repSection = "";
		String errString = "";
		String userId = "";
		
		int currentFormNo = 0;
		int childNodeListLength;
		int ctr=0;
		int count = 0;
		
		boolean flag = false;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;	
		Node parentNode = null;
		Node childNode = null;
	
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
	
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>"); 
		
		try
		{
			
			SimpleDateFormat sdf =  new SimpleDateFormat(genericUtility.getApplDateFormat());
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			System.out.println("Current Form No. :- "+currentFormNo);
				
			switch(currentFormNo)
			{
			case 1 :
				parentNodeList = curDom.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("report_id") && editFlag.equalsIgnoreCase("A"))     // Validation for activity code 
					{
						reportId = checkNull(genericUtility.getColumnValue("report_id", curDom));
						if(reportId == null || reportId.trim().length() == 0)
						{
							errCode = "VTBLNKRPID";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						
					}   //report_id end
					else if(childNodeName.equalsIgnoreCase("ad_code")) 
					{
						adCode = checkNull(genericUtility.getColumnValue("ad_code", curDom));
						
						if(adCode == null || adCode.trim().length() == 0)
						{
							errCode = "VTBLNKADCD";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							String sql = "SELECT  AD_CODE  FROM ALLWDEDN WHERE AD_CODE = ?";
							pstmt =  conn.prepareStatement(sql);
							pstmt.setString(1,adCode.trim());
							rs = pstmt.executeQuery();
							if(!rs.next())
							{
								System.out.println("Ad code is not present . :- ");
								errCode = "VTADCDNTPR";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							if(rs != null) 
							{
								rs.close();
								rs = null;
							}
							if(pstmt != null) 
							{
								pstmt.close();
								pstmt = null;
							}
							
						}
					}else if(childNodeName.equalsIgnoreCase("rep_section")) 
					{
						repSection = checkNull(genericUtility.getColumnValue("rep_section", curDom));
						
						if(repSection == null || repSection.trim().length() == 0)
						{
							errCode = "VTBLNKRPSC";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}  
				}
				 break;
			}
			int errListSize = errList.size();
			count = 0;
			String errFldName = null;
			ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			if(errList != null && errListSize > 0)
			{
				for(count = 0; count < errListSize; count ++)
				{
					errCode = errList.get(count);
					errFldName = errFields.get(count);
					System.out.println("errCode .........." + errCode);
				//	errString = getErrorString(errFldName, errCode, userId);
					errString = itmDBAccessEJB.getErrorString(errFldName, errCode, userId);
					System.out.println("errString........"+errString);
					
					errString = itmDBAccessEJB.getErrorString("", errCode, userId);
					System.out.println("errString........"+errString);
					
					errorType = errorType(conn,errCode);
					return errString;
					
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;
				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}
		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null) 
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{				
					conn.close();
					conn = null;
				}
				
			} 
			catch(Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		return errString;
	}

	public String itemChanged(String xmlString, String xmlString1, String xmlString2,String xmlString3, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		Document dom3=null;
		
	    	
		String valueXmlString = "";
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			if(xmlString2 != null && xmlString2.trim().length() > 0)
			{
				dom2 = parseString(xmlString2);
			}
			if(xmlString3 != null && xmlString3.trim().length() > 0)
			{
				dom3 = parseString(xmlString3);
			}
			System.out.println("xmlString1="+xmlString);
			System.out.println("xmlString2="+xmlString1);
			System.out.println("xmlString3="+xmlString2);
			System.out.println("xmlString4="+xmlString3);
			valueXmlString = itemChanged(dom, dom1, dom2,dom3, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [ReportSpecificationMaster][itemChanged( String, String )] :==>\n" + e.getMessage());
		}
		return valueXmlString;
	}

	public String itemChanged(Document dom, Document dom1, Document dom2, Document dom3, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		System.out.println(" ReportSpecificationMaster itemChanged xtraParams ::------------>"+xtraParams);
		String childNodeName = null;
		String sql = "";
		String adCodeDescr = "";
		String adCode = "";
		String userId = "";
		String tranDate="";
		String termId = "";
		String reportId="";
		int lineNo = 0;
		
		StringBuffer valueXmlString = new StringBuffer();
		int ctr = 0;
		int currentFormNo = 0;
		int childNodeListLength = 0;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		ConnDriver connDriver = new ConnDriver();
		try
		{   
			GenericUtility genericUtility = GenericUtility.getInstance();
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			termId = getValueFromXTRA_PARAMS(xtraParams,"termId");
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
	
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
			valueXmlString.append(editFlag).append("</editFlag> </header>");
			switch(currentFormNo)
			{
			case 1 : 
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				do
				{   
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					ctr ++;
				}while(ctr < childNodeListLength  && ! childNodeName.equals(currentColumn));
				System.out.println("currentColumn = "+currentColumn);
			
				if(currentColumn.trim().equalsIgnoreCase("itm_default") )
				{
					
					  tranDate = simpleDateFormat.format(timestamp).toString();
					  System.out.println("Tran Date 111: "+tranDate.toString());
					  valueXmlString.append("<chg_user>").append("<![CDATA["+userId+"]]>").append("</chg_user>");  
	                  valueXmlString.append("<chg_date>").append("<![CDATA[" + tranDate.trim() +"]]>").append("</chg_date>\r\n");
	                  valueXmlString.append("<chg_term>").append("<![CDATA[" + termId +"]]>").append("</chg_term>\r\n"); 
	                  valueXmlString.append("<line_no protect='1'>").append("<![CDATA[]]>").append("</line_no>\r\n"); 
				}
				else if(currentColumn.trim().equalsIgnoreCase("report_id"))  //Item change for city
				{	
					reportId = checkNull(genericUtility.getColumnValue("report_id", dom));
					
					sql = "SELECT MAX(LINE_NO) AS LINE_NO FROM REP_SPECIFIC_AD WHERE REPORT_ID = ?";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,reportId.trim());
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						lineNo = rs.getInt(1) ;
					}
					
					lineNo = lineNo+ 1 ;
					
					if(rs != null) 
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null) 
					{
						pstmt.close();
						pstmt = null;
					}
					
	                valueXmlString.append("<line_no>").append("<![CDATA[" + lineNo +"]]>").append("</line_no>\r\n"); 
					
				}
				else if(currentColumn.trim().equalsIgnoreCase("ad_code"))  //Item change for ad_code
				{	
						adCode = checkNull(genericUtility.getColumnValue("ad_code", dom));
					
						sql = "SELECT AD_CODE, DESCR FROM ALLWDEDN WHERE AD_CODE = ?";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,adCode.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							adCode =  rs.getString(1);
							adCodeDescr = rs.getString(2);
						}
						if(rs != null) 
						{
						rs.close();
						rs = null;
						}
						if(pstmt != null) 
						{
						pstmt.close();
						pstmt = null;
						}

					
	                    //valueXmlString.append("<ad_code>").append("<![CDATA[" + adCode +"]]>").append("</ad_code>\r\n"); 
	                    valueXmlString.append("<descr>").append("<![CDATA[" + adCodeDescr +"]]>").append("</descr>\r\n");
					
				}
				
				valueXmlString.append("</Detail1>");
				break;       
		
			}
			valueXmlString.append("</Root>");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+ e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
  
			try
			{
				if(rs != null) 
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null) 
				{
					pstmt.close();
					pstmt = null;

				}
				if(conn != null)
				{					
					conn.close();
					conn = null;	
				}
				
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}

	private String errorType(Connection conn , String errorCode)
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = "SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ?";
			pstmt = conn.prepareStatement(sql);			
			pstmt.setString(1,errorCode);			
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}		
		return msgType;
	}
	
 
}
