package ibase.webitm.ejb.sys;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import ibase.utility.*;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

import org.w3c.dom.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class SysGenPassword extends ValidatorEJB implements  SysGenPasswordLocal , SysGenPasswordRemote // SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate() 
	{
	}

	public void ejbPassivate() 
	{
	}
	*/
	public String preSaveForm()throws RemoteException,ITMException
	{
		return "";
	}

	public String preSaveForm(String xmlString1,String domId,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		Document dom = null;
		String flag="PRE";
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				executepreSaveForm(xmlString1,domId,objContext,editFlag,xtraParams,flag,conn);
			}			
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :SysGenPassword ::" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return "";
	}
	public String postSaveRec(String xmlString1, String domId, String objContext, String editFlag, String xtraParams, Connection conn) throws RemoteException, ITMException
	{
		Document dom = null;
		String saveRec = "",flag="POST";
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				executepreSaveForm(xmlString1,domId,objContext,editFlag,xtraParams,flag,conn);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :WoPostSaveEJB :postSaveRec(): " + e.getMessage()+ ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return saveRec;
	}
	private String executepreSaveForm(String xmlString1, String domID,String objContext,String editFlag, String xtraParams,String flag, Connection conn)throws RemoteException,ITMException
	{
		System.out.println("flag : " + flag);
		System.out.println("editFlag : " + editFlag);
		GenericUtility genericUtility = GenericUtility.getInstance(); 
		String finalStr = "";
		Document dom = null;
		StringBuffer valueXmlString = new StringBuffer();
		String childNodeValue = null,currentColumn ="";
		String columnValue = "",xmlStringComp ="",acctLock ="";
		String userId="", errCode = "",resultString = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="",formatCode ="",refSer ="",tranIdCol ="",eventContext ="";
		String refId ="",objName ="",genPassWord ="",winName ="";
		int lineNo =0, k=0;
		int ctr=0,currentFormNo =0,childNodeListLength =0,cnt =0;
		StringBuffer commInfo = new StringBuffer();
		String sendTo ="";
		String sendCC ="",acctLockPrev ="";
		String userType ="",code ="";
		try
		{
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			dom = parseString(xmlString1);
			objName = "user";
			winName = "w_user";

			NodeList parentNodeList = null;
			NodeList childNodeList = null;
			Node parentNode = null;
			Node childNode = null;
			String childNodeName = null;
			parentNodeList = dom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			for(int i=0; i<childNodeList.getLength(); i++)
			{
					childNode = childNodeList.item(i);
					childNodeName = childNode.getNodeName();
					if(childNode.getNodeName().equalsIgnoreCase("acct_lock"))
					{
						if (childNode.getFirstChild() != null)
						{
							acctLock =  childNode.getFirstChild().getNodeValue();
							//System.out.println("Node Value1 : " + childNode.getFirstChild().getNodeValue());
						}
					}
					if(childNode.getNodeName().equalsIgnoreCase("user_type"))
					{
						if (childNode.getFirstChild() != null)
						{
							userType =  childNode.getFirstChild().getNodeValue();
							//System.out.println("Node Value1 : " + childNode.getFirstChild().getNodeValue());
						}
					}
					if(childNode.getNodeName().equalsIgnoreCase("code"))
					{
						if (childNode.getFirstChild() != null)
						{
							code =  childNode.getFirstChild().getNodeValue();
							//System.out.println("Node Value1 : " + childNode.getFirstChild().getNodeValue());
						}
					}
			}
			sql="select acct_lock from users where code = '"+code+"' ";
				//System.out.println("[SysGenPasswordEJB] SQL..................."+sql);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					acctLockPrev = rs.getString("acct_lock");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
			if(("E".equalsIgnoreCase(editFlag.trim()) && "N".equalsIgnoreCase(acctLock.trim()) && "Y".equalsIgnoreCase(acctLockPrev.trim())) || (("A".equalsIgnoreCase(editFlag.trim()) && "POST".equalsIgnoreCase(flag.trim()))))
			{
				if("A".equalsIgnoreCase(editFlag))
				{
					eventContext = "new_password";
				}
				else
				{
					eventContext = "acct_unlock";
				}
				sql="SELECT comm_format FROM system_events WHERE obj_name = '"+objName+"' "
					+   " and event_context = '"+eventContext+"' ";
				//System.out.println("[SysGenPasswordEJB] SQL..................."+sql);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					formatCode = rs.getString("comm_format");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				sql="SELECT ref_ser, tran_id_col FROM transetup WHERE tran_window = '"+winName+"' ";
				//System.out.println("[SysGenPasswordEJB] SQL..................."+sql);
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					refSer = rs.getString("ref_ser");
					tranIdCol = rs.getString("tran_id_col");
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				if(refSer == null ) refSer ="   ";
				if(tranIdCol == null ) tranIdCol ="   ";
				if((refId == null) || refId.trim().length() == 0)
				{
					refId = "newrefno";
				}
				PassWordGenerator passWordGenerator =  new PassWordGenerator();
				genPassWord = passWordGenerator.password(userId);
				passWordGenerator = null;
				valueXmlString.append("<pass_wd>").append("<![CDATA[" + genPassWord + "]]>").append("</pass_wd>");

					commInfo.append("<ROOT><TRANS_INFO>");
					commInfo.append("<OBJ_NAME><![CDATA[" + objName + "]]></OBJ_NAME>");
					commInfo.append("<REF_SER><![CDATA[" + refSer + "]]></REF_SER>");
					commInfo.append("<REF_ID><![CDATA[" + refId + "]]></REF_ID>");
					commInfo.append("<LINE_NO><![CDATA[" + lineNo + "]]></LINE_NO>");
					commInfo.append("<XSL_FILE_NAME></XSL_FILE_NAME></TRANS_INFO>");
					commInfo.append("<MAIL><EMAIL_TYPE>page</EMAIL_TYPE><ENTITY_CODE>BASE</ENTITY_CODE>");
					commInfo.append("<ENTITY_TYPE>"+userType+"</ENTITY_TYPE>");
					commInfo.append("<TO_ADD>"+sendTo+"</TO_ADD>");
					commInfo.append("<CC_ADD>"+sendCC+"</CC_ADD>");
					commInfo.append("<FORMAT_CODE>"+formatCode+"</FORMAT_CODE>");
					commInfo.append("<ATTACHMENT><BODY></BODY><LOCATION></LOCATION></ATTACHMENT>");
					
					if("E".equalsIgnoreCase(editFlag))
					{
						xmlStringComp =xmlString1.substring(0,xmlString1.indexOf("<pass_wd>"));
						xmlStringComp =xmlStringComp +  xmlString1.substring(xmlString1.indexOf("</pass_wd>")+10,xmlString1.indexOf("</Detail1>"));
						xmlStringComp = xmlStringComp + valueXmlString.toString() + xmlString1.substring(xmlString1.indexOf("</Detail1>"));
					}
					else
					{
						xmlStringComp =xmlString1.substring(0,xmlString1.indexOf("<pass_wd/>"));
						xmlStringComp =xmlStringComp +  xmlString1.substring(xmlString1.indexOf("<pass_wd/>")+10,xmlString1.indexOf("</Detail1>"));
						xmlStringComp = xmlStringComp + valueXmlString.toString() + xmlString1.substring(xmlString1.indexOf("</Detail1>"));
					}
					//System.out.println("[SysGenPasswordEJB] xmlStringComp..................."+xmlStringComp);
					commInfo.append("</MAIL><XML_DATA>"+xmlStringComp+"</XML_DATA>");
					commInfo.append("</ROOT>");
					//System.out.println("[SysGenPasswordEJB] commInfo..................."+commInfo);
					EMail email = new EMail();
					email.sendMail(commInfo.toString(), "ITM"); 
					email = null;
					if(errCode.trim().length() == 0 || errCode == null )
					{
						errCode = "<Root><Message>Success</Message></Root>";
						sql= "update users set pass_wd ='"+genPassWord+"'  where code = '"+code+"' " ;
						//System.out.println("[SysGenPasswordEJB] SQL..................."+sql);
						pstmt = conn.prepareStatement(sql);
						int upd = pstmt.executeUpdate();
						if(upd > 0)
						{
							System.out.println("pass word updated...................");
						}
						pstmt.close();
						pstmt = null;
					}
			}
		}
		catch (RemoteException e1) {
			e1.printStackTrace();
		} 
		catch (ITMException e1) {
			e1.printStackTrace();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return errCode;
	}
}
