package A10Park;

import java.io.*;
import java.sql.*;
import java.text.*;
import java.lang.Math;
import java.util.*;
import java.util.Random;
import java.util.Date;
import sun.net.smtp.SmtpClient;

import javax.servlet.*;
import javax.servlet.http.*;

public class A10_CreateUser extends HttpServlet {

    private Properties connectionProperties = new Properties();
    private Driver     driver               = null;
    private String     driverName           = null;
    private String     jdbcURL              = null;


    public void init(ServletConfig cfg) throws ServletException {
        super.init(cfg);
        {
        	String user, pw;
	      ServletContext ctx = getServletContext();
         driverName = ctx.getInitParameter("gb.DBdriver");
         jdbcURL = ctx.getInitParameter("gb.DBconn_string");
         user = ctx.getInitParameter("gb.DBusername");
         if( user != null ) {
         	connectionProperties.put("user", user);
         }
         pw = ctx.getInitParameter("gb.DBpassword");
         if( pw != null ) {
         	connectionProperties.put("password", pw);
         }
         try {
         	driver = (Driver)Class.forName(driverName).newInstance();
        	}
         catch( Exception e ) {
         	throw new ServletException("Unable to load driver: " + e.getMessage());
         }
       }
   }


      public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

		  response.setContentType("text/html");
    	  PrintWriter out = response.getWriter();
        ResultSet results;
        Statement stmt;
		  Connection conn = null;

        try {
	      ServletContext ctx = getServletContext();
 	     		String errorMessage = null;
         	conn = DriverManager.getConnection(jdbcURL, connectionProperties);
         	stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

				if(request.getParameter("username")!=null)
				{
					String username = request.getParameter("username");
					String password = request.getParameter("password");
					String email = request.getParameter("email");
         		results = stmt.executeQuery("SELECT * FROM calendar WHERE username='" + username + "'");

					results.last();
					int numberOfRows = results.getRow();

					if(numberOfRows >= 1)
						out.println("User already exists, cannot create this user<br />");
					else
					{

	 					Random generator = new Random();
	 					long topLimit = 99999999;
	 					long lowLimit = 10000;
	 					long difference = topLimit - lowLimit;
	 					long frac = (long)(difference * generator.nextDouble());
	 					long verifynum = (int)(frac + lowLimit);

	   				Date now = new Date();

                  float createTime = now.getTime();
                  createTime = createTime/3600000;
                  //createTime = createTime/60;
                  //createTime = createTime/60;
                  createTime = Math.round(createTime);
                  out.println("Current time: " + createTime);

						stmt.executeUpdate("INSERT into calendar (username, password, email, sched, verified, createTime) VALUES ('" + username + "', '" + password + "', '" + email + "', 'M:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;T:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;W:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;T:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;F:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;'," + "'" + verifynum + "', '" + createTime + "')");
						stmt.close();

						SmtpClient smtp = new SmtpClient();  // assume localhost
						String from = "Group-G-Scheduler";
      				smtp.from(from);
      				smtp.to(email);

      				PrintStream msg = smtp.startMessage();
				      msg.println("To: " + email);  // so mailers will display the To: address
      				msg.println("Subject: Group G Account Registration Verification");
      				msg.println();

						msg.println("Thank you for creating an account with Group G's Scheduler.");
						msg.println("You registered as " + username);
						msg.println("To verify your account please go to " + ctx.getInitParameter("gb.VerifyUser") + "?username=" + username + "&verifyID=" + verifynum);


      				msg.println();
      				smtp.closeServer();

						out.println("User has been created");
						out.println("An email has been sent to you, must verify it first before your account is activated");
					}
				}
     	}
      catch( SQLException e ) {
      	out.println("A database error occurred: " + e.getMessage());
      }
      finally {
      	if( conn != null ) {
         	try { conn.close(); }
            catch( SQLException e ) { }
				out.println("</body></html>");
         }
     }

  }
}
