package zall.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import zall.ZalleryAjax;
import zall.bean.User;
import zall.util.ZalleryEmail;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;
import zutil.log.LogUtil;

public class RegisterAction extends ZalleryAction{
	private static final Logger logger = LogUtil.getLogger();

	public RegisterAction() {
		super("register");
	}
	
	@Override
	public void handleRequest(DBConnection db, HttpServletRequest request, HttpServletResponse response, HttpSession session,
			PrintWriter out, User user, UserMessage msgs) throws SQLException, IOException {

		if( request.getParameter("email") == null ){
			msgs.add(MessageType.ERROR, "Please provide a valid email!");
			return;
		}
		if( User.emailExists(request.getParameter("email"), db) ){
			msgs.add(MessageType.ERROR, "An account with that email already exists!");
			return;
		}					
		user = new User();
		user.setEmail( request.getParameter("email") );
		user.setPassword( request.getParameter("password") );
		user.setName( request.getParameter("name") );
		user.save(db);
		ZalleryEmail.sendVerificationEmail( user );
		logger.info("Registered new user: "+user.getName()+".");
		session.setAttribute("user", user);
		if(out != null)	out.println("{ \"id\":"+user.getId()+" }");
		else			msgs.add(MessageType.INFO, "Your account has successfully been created. A verification email has been sent to your email, please click the link to continue.");

	}

}
