/********************************************
  This class is a servlet and a mail client.  It gets information for a database connection
  from the DD, and gets the account information from the user.  If the account information is
  valid, it sends an email to the email address given for the account with the username, password,
  a random confirmation number, and a link to the verification page.  It then directs the user to 
  the login screen.  If the account information is invalid, it sends the user back to the 
  account creation screen.

  @author Anthony Furst
  @version CISC474 A10
*/

package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.sql.*;

import sun.net.smtp.SmtpClient;

public class CreateAccount extends HttpServlet {
    
    /** Performs all functionality for the servlet
	@param request A servlet request object
	@param response A servlet response object
    */
    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
	throws IOException, ServletException {
	String username;
	String password;
	String url;

	username = getServletContext().getInitParameter("user");
	password = getServletContext().getInitParameter("passwd");
	url = getServletContext().getInitParameter("url");

	Checker accountCheck = new Checker();

	String name = request.getParameter("username");
	String pw = request.getParameter("password");
	String email = request.getParameter("email");
	boolean validName = true;

	accountCheck.makeConnection(username, password, url);
	validName = accountCheck.performQuery(name, pw, email);	

	if (validName) {
	    //All this code sets up the mail connetion and sends the email
	    String number = accountCheck.getNumber(name);

	    response.setContentType("text/plain");
	    PrintWriter out = response.getWriter();
	    
	    SmtpClient smtp = new SmtpClient();
	    smtp.from(request.getParameter("replyto"));
	    smtp.to(email);
	    PrintStream msg = smtp.startMessage();
	    
	    msg.println("To: " + email);
	    msg.println("Subject: Confirmation Email");
	    msg.println();

	    msg.println("Username: " + name);
	    msg.println("Password: " + pw);
	    msg.println("Confirmation Number: " + number);
	    msg.println();
	    msg.println("Click here to verify");
	    msg.println("http://porsche.cis.udel.edu:8113/Schedule-v2/verification.html");
	    
	    smtp.closeServer();

	    accountCheck.closer();
	 
	    RequestDispatcher view = request.getRequestDispatcher("login.html");
	    view.forward(request, response);
	}
	else {
	    accountCheck.closer();
	    
	    RequestDispatcher view = request.getRequestDispatcher("accountError.html");
	    view.forward(request, response);
	}
    }
}
