

/********************************************************
	Title     : WorkLocationMaster.java
	Date      : 03-SEP-2014
	Developer : CHETNA SHAHU
	Purpose   : Define the work loactions  for employee
********************************************************/

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 WorkLocationMaster  extends ValidatorEJB implements WorkLocationMasterLocal,WorkLocationMasterRemote {
	
	
	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
	{
		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 userId = "";
		String errorType = "";
		String childNodeName = null;
		String errCode = "";
		String wrkLocCode = "";
		String descr = "";
		String stateCode = "";
		String active = "";
		String errString = "";
		
		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("work_loc_code") && editFlag.equalsIgnoreCase("A") )
					{
						wrkLocCode = checkNull(genericUtility.getColumnValue("work_loc_code", curDom));
						if(wrkLocCode == null || wrkLocCode.trim().length() == 0)
						{
							String keyFlag = "M";
							String sqlStr = "SELECT KEY_FLAG AS KEY_FLAG FROM TRANSETUP WHERE TRAN_WINDOW = 'w_work_location'";
							pstmt =  conn.prepareStatement(sqlStr);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								keyFlag =  rs.getString("KEY_FLAG");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							if (keyFlag == null || keyFlag.trim().length() == 0 || keyFlag.equalsIgnoreCase("M"))
							{
								errCode = "VMWRKLOC01";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						else
						{
							flag = isRecordExist(conn," WORK_LOCATIONS "," WHERE WORK_LOC_CODE = '"+wrkLocCode.trim()+"' ");
							if(flag == true)
							{
								errCode = "VMWRKLOC02";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					}   //work_loc_code end
					else if(childNodeName.equalsIgnoreCase("descr")) // Work Location for  Description 
					{
						 descr = checkNull(genericUtility.getColumnValue("descr", curDom));
						
						if(descr == null || descr.trim().length() == 0)
						{
							errCode = "VMWRKLOC03";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					} // End of descr 
					else if(childNodeName.equalsIgnoreCase("city")) // Validation for state_code
					{
						String city = checkNull(genericUtility.getColumnValue("city", curDom));
						
						if(city == null || city.trim().length() == 0)
						{
							errCode = "VMWRKLOC05";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							flag = isRecordExist(conn," STATION "," WHERE DESCR = '"+city.trim()+"' ");
							if(flag == false)
							{
								errCode = "VMWRKLOC06";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					} // End of city 
					else if(childNodeName.equalsIgnoreCase("state_code")) // Validation for state_code
					{
						stateCode = checkNull(genericUtility.getColumnValue("state_code", curDom));
						
						if(stateCode == null || stateCode.trim().length() == 0)
						{
							errCode = "VESTATCD1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							flag = isRecordExist(conn," STATE "," WHERE STATE_CODE = '"+stateCode.trim()+"' ");
							if(flag == false)
							{
								errCode = "VESTATCD2";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					} // End of state_code 
					else if(childNodeName.equalsIgnoreCase("active")) // Validation for active
					{
						active = checkNull(genericUtility.getColumnValue("active", curDom));
						
						if(active == null || active.trim().length() == 0)
						{
							errCode = "VMWRKLOC04";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					} // End of active 
				}
				 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(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();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		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
		{   
			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);
			}
			System.out.println("xmlString1="+xmlString);
			System.out.println("xmlString2="+xmlString1);
			System.out.println("xmlString3="+xmlString2);
			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [DistributionRoute][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("xtraParams ::------------>"+xtraParams);
		String childNodeName = null;
		String sql = "";
		String city = "";
		String stateCodeDescr = "";
		String stateCode = "";
		String userId = "";
		String tranDate="";
		String termId = "";
		
		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("<active>").append("<![CDATA[Y]]>").append("</active>");  
					  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"); 
				}
				else if(currentColumn.trim().equalsIgnoreCase("city"))  //Item change for city
				{	
					city = checkNull(genericUtility.getColumnValue("city", dom));
					if(city != null && city.trim().length() > 0)
					{
						sql = "SELECT STATE.STATE_CODE  , STATE.DESCR FROM STATION , STATE WHERE  STATION.STATE_CODE = STATE.STATE_CODE  AND STATION.DESCR = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,city.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							stateCode =  rs.getString(1);
							stateCodeDescr = rs.getString(2);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

					
	                    valueXmlString.append("<city>").append("<![CDATA[" + city +"]]>").append("</city>\r\n"); 
	                    valueXmlString.append("<state_code>").append("<![CDATA[" + stateCode +"]]>").append("</state_code>\r\n"); 
	                    valueXmlString.append("<state_descr>").append("<![CDATA[" + stateCodeDescr +"]]>").append("</state_descr>\r\n");
					}
					else
					{
						 valueXmlString.append("<city>").append("<![CDATA[]]>").append("</city>\r\n"); 
						 valueXmlString.append("<state_code>").append("<![CDATA[]]>").append("</state_code>\r\n"); 
		                 valueXmlString.append("<state_descr>").append("<![CDATA[]]>").append("</state_descr>\r\n");
					}//end of city
				}
				else if(currentColumn.trim().equalsIgnoreCase("state_code"))  //Item change for state_code
				{	
					 stateCode = checkNull(genericUtility.getColumnValue("state_code", dom));
					if(stateCode != null && stateCode.trim().length() > 0)
					{
						sql = "SELECT STATE.DESCR AS STATE_DESCR FROM STATE WHERE STATE.STATE_CODE  = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,stateCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							stateCodeDescr = rs.getString("STATE_DESCR");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

					
	                    valueXmlString.append("<state_code>").append("<![CDATA[" + stateCode +"]]>").append("</state_code>\r\n"); 
	                    valueXmlString.append("<state_descr>").append("<![CDATA[" + stateCodeDescr +"]]>").append("</state_descr>\r\n");
					}
					else
					{
						 valueXmlString.append("<state_code>").append("<![CDATA[ ]>").append("</state_code>\r\n"); 
		                 valueXmlString.append("<state_descr>").append("<![CDATA[ ]>").append("</state_descr>\r\n");
					

							
					}//end of state_code
				}
				
				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(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();
	}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}

	private String errorType(Connection conn , String errorCode)
	{
		String msgType = "E";
		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;
	}
	
	
	public boolean isRecordExist(Connection conn , String tableName, String condition)
	{
	
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		String sql="";
		boolean isExist=false;
		int recCount=0;
		
		
		try
		{	
			
			sql = " SELECT  COUNT(*)  FROM  "+tableName +"  "+condition;
			pstmt =  conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				recCount=rs.getInt(1);
			
			}
			if(recCount>0)
			{
				isExist=true;
				
			}
			else
			{
				isExist=false;
			
			}
				
		}
		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();
			}
		}		
		
		System.out.print("---------Final--isExist-------"+isExist);
		return isExist;
	}
	
 
}
