package src.hibernatebb.web;

import src.hibernatebb.discussion.Topic;
import src.hibernatebb.discussion.Post;
import src.hibernatebb.discussion.BoardManager;
import src.hibernatebb.discussion.User;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.lang.*;

/**
 * 
 * @author Jason Fillo
 * @author Peter Deschere
 * @version 1.0
 *
 */
public class NewUserServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
	throws IOException, ServletException {
	
	RequestDispatcher view;
	HttpSession session = request.getSession();

	String userName = request.getParameter("newname");
	String password = request.getParameter("password");
	String cpassword = request.getParameter("cpassword");

    request.setAttribute("name", userName);
	
	BoardManager bm = new BoardManager();
	
	User u = new User(userName,password);
	
	if (!password.equals(cpassword)) {
	
		request.setAttribute("errornew","Password and Confirmation do not match!");
		view = request.getRequestDispatcher("login.jsp");
		view.forward(request, response);
		
	} else if (bm.loadUser(userName) != null) {
		request.setAttribute("errornew","Invalid username!");
		view = request.getRequestDispatcher("login.jsp");
		view.forward(request, response);
		
	} else {
		
	List<String> topics = new ArrayList<String>();

	try {
		bm.saveUser(u);

	    List t = bm.getTopics();
	    Iterator it = t.iterator();
	    
	    
	    while(it.hasNext()) {
		topics.add(((Topic)it.next()).getID());
	    }
	    
	}
	catch(Exception e) {
	    topics.add(new String(e.toString()));
	    }
	
	
	request.setAttribute("topics", topics);

	view = request.getRequestDispatcher("main.jsp");
	view.forward(request, response);
	
	}
		
    }
}

