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.security.MessageDigest;
import java.util.*;
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 encryptPwd="";//Gulzar on 4/16/2012
		String encryptPwdSha="";//Gulzar on 4/16/2012
		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;

					
					/**********Modified by Rakesh kumar on 13/04/12 ***********/ 
					//convertIntoSHA256(genPassWord) used to convert Encrypted password
					
					encryptPwd = encryptPassword(genPassWord);
					System.out.println("encryptPwd =["+encryptPwd+"]");
					
				    encryptPwdSha = convertIntoSHA256(genPassWord);
					System.out.println("encryptPwdSha =["+encryptPwdSha+"]");

					if(errCode.trim().length() == 0 || errCode == null )
					{
						errCode = "<Root><Message>Success</Message></Root>";
						//Commented and changes by Rakesh
						//sql= "update users set pass_wd ='"+genPassWord+"'  where code = '"+code+"' " ;
						
						/**********Changed by Rakesh kumar on 13/04/12 ***********/ 
						//Sql Query for Encrypted passward
						sql= "update users set pass_wd_sha = ?, pass_wd = ? where code = ? " ;
						
						//System.out.println("[SysGenPasswordEJB] SQL..................."+sql);
						pstmt = conn.prepareStatement(sql);
						pstmt.setString( 1, encryptPwdSha );
						pstmt.setString( 2, encryptPwd );
						pstmt.setString( 3, code );
						int upd = pstmt.executeUpdate();
						if(upd > 0)
						{
							System.out.println("password updated...................");
						}
						pstmt.close();
						pstmt = null;
						//End changes by Rakesh
					}
			}
		}
		catch (RemoteException e1) {
			e1.printStackTrace();
			throw new ITMException(e1);
		} 
		catch (ITMException e1) {
			e1.printStackTrace();
			throw new ITMException(e1);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errCode;
	}
	 /*** written by Rakesh Kumar on 13/04/12 ***
	  *** convertIntoSHA256(String dpwd) method for converted into Encrypted password format ****/
	private String convertIntoSHA256(String dpwd) throws Exception
    {
		System.out.println("dpwd =["+dpwd+"]");
        StringBuffer hexString = new StringBuffer();
        try
        {
            MessageDigest md = MessageDigest.getInstance("SHA-256"); //$NON-NLS-1$
			md.update(dpwd.getBytes(CommonConstants.ENCODING)); //$NON-NLS-1$
			byte byteData[] = md.digest();
			//convert the byte to hex format method 1
			for (int i=0;i<byteData.length;i++)
			{
				String hex=Integer.toHexString(0xff & byteData[i]);
				if(hex.length()==1) hexString.append('0');
				hexString.append(hex);
			}
            //System.out.println("Hex format : " + hexString.toString());
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        return hexString.toString();
    }
	
	private String encryptPassword(String as_passwd) throws Exception
	{
		System.out.println("SysGenPassword..................encrypt..............."); 
		String ls_return = ""; 
		try
		{
			System.out.println( "Encrypting Password....." ); 
			int li_len, li_count, li_Seed, li_passAsc;
			li_len = as_passwd.length();
			for(li_count = 0; li_count < li_len;li_count++)
			{
				Random li_Seed_r = new Random();
				li_Seed = li_Seed_r.nextInt(10);
				li_passAsc  =(int) as_passwd.charAt(li_count);
				li_passAsc = li_passAsc + li_Seed + li_count;
				ls_return +=""+(char)(li_passAsc) +""+ (char)(li_Seed + li_count); 
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception: SysGenPassword: encrypt:==>\n"+e.getMessage()); 
			//throw e;
		}
		System.out.println("SysGenPassword..................encrypt.......["+ls_return+"]....");
		return ls_return;
	}
	//End changes by Rakesh
	
}
