/* this servlet will be called by the register page. after the user submits the registration form, his selected login will be searched in the database, and he will be registered if nobody has that login. for this, a random passed will be gererated which will be mailed to him and he can login using that password. this is essentially to verify his email address. */


import java.io.*;	
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.lang.*;
import java.util.*;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Control passes to the doGet method of this class from the registration page. All data entered by user are verified by methods of this class
 * and entry in made for the usre in the database after all constraints are satisfied.
 * @author      Nilesh Agarwal
 * @version     1.00, 09/10/2001
 */ 

public class RegisterServlet extends HttpServlet
{ 
    public String login1, firstName1, lastName1, email1, gender1, address1, city1, day1, month1, year1;
    public boolean repeat=true;
    

    /**
     * <code>doGet</code> - This method uses methods of class QueryEngine to check for repetiton of username and email address.
     * After verifying all data, it registers the user.
     * @param HttpServletRequest request
     * @param HttpServletResponse response
     */      

    public void doPost (HttpServletRequest request, 
			HttpServletResponse response) 
	throws ServletException, IOException {
	PrintWriter out;
	response.setContentType("text/html");
	
	String login = request.getParameter("userLogin");     // userLogin field of the form
	String firstName= request.getParameter("firstName");//first name of user
	String lastName = request.getParameter("lastName");//first name of user
	String email = request.getParameter("email");//first name of user
	String gender = request.getParameter("gender");//first name of user
	String address = request.getParameter("address");//first name of user
	String city = request.getParameter("city");//first name of user
	String day = request.getParameter("day");//first name of user
	String month = request.getParameter("month");//first name of user
	String year = request.getParameter("year");//first name of user
	String whereFrom= request.getParameter("whereFrom");
	String password="test", monthValue, date;
	if (!(whereFrom==null)){
	    repeat=false;
	}
	
	System.out.println("login:"+login ); // printing for checking, later to be commented
	if (login!=null)
	    login1=login;
	System.out.println("firstname:"+firstName ); // ----do------
	System.out.println("lastName:"+lastName ); // ----do------
	System.out.println("email:"+email);
	if (email!=null)
	    email1=email;
	System.out.println("address"+address);
	System.out.println("city"+city);
	System.out.println("day"+day);
	
	if (repeat){
	    System.out.println("repeat= true");
	}
	else {
	    System.out.println("repeat= false");
	}
	
	out=response.getWriter();
	
	//NOTE A FUNCTION FOR UserQueryEngine CLASS HERE
	// we need to check of the login name is already present or not. if yes, go back to register page. this is done be using the function isLoginPresent(String login) in UserQueryEngine class
	boolean checkLogin=(SharedObjects.qe).isLoginPresent(login1);
	boolean checkEmail=(SharedObjects.qe).isEmailPresent(email1);
	if (checkLogin || checkEmail){
	    if (checkLogin){
		if (repeat){ // initially repeat=true. after we promt the user for the first time
		    // for giving another login name, we save the already eneterd data.
		    // and we make repeat=false.
		    System.out.println("I am here=> rs was not null");
		    firstName1=firstName;  // these temp variables are for storing the values
		    lastName1=lastName;    // te user entered so that we may remember them
		    //email1=email;
		    gender1=gender;
		    address1=address;
		    city1=city;
		    day1=day;
		    month1=month;
		    year1=year;
		}
		else { // no need to save again coz we already saved it
		    repeat=false;
		}
		
		//NOTE A FUNCTION FOR UserPageGenerator CLASS HERE
		UserPageGenerator.enterAnotherLogin(out, login); // this functin does what is written below. It takes as arguement current value of login. 
		// generate a page saying that the login has already been taken. ask for another login name, rest of the fields remain same so no need to show them again. this will generate a form with action to the post methos of this very servlet
	    }
	    if (checkEmail){
		if (repeat){ // initially repeat=true. after we promt the user for the first time
		    // for giving another email address, we save the already entered data.
		    // and we make repeat=false.
		    System.out.println("I am here=> rs was not null");
		    firstName1=firstName;  // these temp variables are for storing the values
		    lastName1=lastName;    // te user entered so that we may remember them
		    email1=email;
		    gender1=gender;
		    address1=address;
		    city1=city;
		    day1=day;
		    month1=month;
		    year1=year;
		}
		else { // no need to save again coz we already saved it
		    repeat=false;
		}
		
		//NOTE A FUNCTION FOR UserPageGenerator CLASS HERE
		UserPageGenerator.enterAnotherEmail(out, email); // this functin does what is written below. It takes as arguement current value of login. 
		// generate a page saying that the login has already been taken. ask for another login name, rest of the fields remain same so no need to show them again. this will generate a form with action to the post methos of this very servlet
	    }
	}	
	else
	    {
		if (!repeat){// implies we had saved the posted data. now move them back to original variables
		    System.out.println("I am here=> rs was null");
		    
		    firstName=firstName1;  // these temp variables are for storing the values
		    lastName=lastName1;    // te user entered so that we may remember them
		    email=email1;
		    gender=gender1;
		    address=address1;
		    city=city1;
		    day=day1;
		    month=month1;
		    year=year1;
		}
		password=generatePassword(login);  // this is a random password generator function which will generate a password.
		//		password="test";
		System.out.println("password= "+password);
	
		monthValue= getMonthValue(month);
		// 2. change the date in the required format as stored in sql table
		date = day+"-"+monthValue+"-"+year;
		System.out.println("date= "+date);
		// NOTE UserQueryEngine CLSSS FUNCTION HERE
		(SharedObjects.qe).addUserInfo(login, password, firstName, lastName, email, gender, address, city, date); // this will add user's information to the database
		System.out.println("date== "+date);
		String from=Config.sysadEmail;
		String recipients[]={email};
		String subject="Your Auction Registration Password";
		String message="Thank You for registering at our site.\n";
		message+="Your Login : "+login+"\n";
		message+="Your Password : "+ password+"\n";
		message+="Logon and enjoy bidding.\n";
		message+="Visit : "+ Config.servletUrl+"LoginServlet\n";
		message+="Have a great time!!!\n";
		

		mailUserHisPassword(recipients, subject, message, from);
		// NOTE UserPageGenerator CLASS FUNCTION
		UserPageGenerator.userRegisteredPage(out, login, email);
		// 5. generate a page saying that the user have been registerd and his password has been mailed to him. provide a link to the main page.


	    }
    }


    /**
     * This method generates a random password depending upon the login name which user selects.
     * @param String login 
     */      

    public static String generatePassword(String login){
	Integer i1=new Integer(login.hashCode());
	return Integer.toHexString(i1.intValue()).intern();
    }
    
    /**
     * This method uses javax.mail, javax.mail.http and javax.activation classes and mails user his login and password at the email address 
     * given by him during registration.
     * @param String recipients[]  -- array of String having users email ID.
     * @param String subject       -- subject of mail
     * @param String message       -- message to be send 
     * @param String from          -- sender's emails address
     */      

    public static void mailUserHisPassword( String recipients[ ], String subject, String message, String from){
	
	try{
	    
	    boolean debug = false;
	    //Set the host smtp address
	    Properties props = new Properties();
	    props.put("mail.smtp.host", Config.smtpAddress);
	    
	    // create some properties and get the default Session
	    Session mailSession = Session.getDefaultInstance(props, null);
	    mailSession.setDebug(debug);
	    
	    // create a message
	    Message msg = new MimeMessage(mailSession);
	    
	    // set the from and to address
	    InternetAddress addressFrom = new InternetAddress(from);
	    msg.setFrom(addressFrom);
	    
	    InternetAddress[] addressTo = new InternetAddress[recipients.length];
	    for (int i = 0; i < recipients.length; i++)
		{
		    addressTo[i] = new InternetAddress(recipients[i]);
		}
	    msg.setRecipients(Message.RecipientType.TO, addressTo);
	    
	    
	    // Optional : You can also set your custom headers in the Email if you Want
	    msg.addHeader("MyHeaderName", "myHeaderValue");
	    
	    // Setting the Subject and Content Type
	    msg.setSubject(subject);
	    msg.setContent(message, "text/plain");
	    Transport.send(msg);
	}catch(MessagingException exc){System.out.println(exc);}
    }
    
    /**
     * This method takes a month name as an arguement and returns the corrosponding month number.
     * @param String month          -- month name
     */          

    public String getMonthValue(String month){
	switch((Integer.valueOf(month)).intValue()){
	case 1:
	    return "Jan";
	case 2:
	    return "Feb";
	case 3:
	    return "Mar";
	case 4:
	    return "Apr";
	case 5:
	    return "May";
	case 6:
	    return "Jun";
	case 7:
	    return "Jul";
	case 8:
	    return "Aug";
	case 9:
	    return "Sep";
	case 10:
	    return "Oct";
	case 11:
	    return "Nov";
	default:
	    return "Dec";
	}
    }
}














