package zall.action.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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

import zall.ZalleryAjax;
import zall.action.ZalleryAction;
import zall.bean.User;
import zall.util.ZalleryEmail;
import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection;

public class VerifyEmailAction extends ZalleryAction{

	public VerifyEmailAction() {
		super("verfemail", true);
	}

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

		User verifiedUser = User.load(db, Long.parseLong(request.getParameter("id")));
		if (verifiedUser != null) {
			if (verifiedUser.verifyEmail(request.getParameter("hash"))) {
				if (verifiedUser.isEnabled())
					if (out != null) out.println("{ }");
					else msgs.add(MessageType.INFO, "Your email has been successfully verified");
				else {
					ZalleryEmail.sendNewUserRegistrationToAdmin(verifiedUser, db);
					if (out != null) out.println("{ }");
					else
						msgs.add(MessageType.INFO, "Your email has been successfully verified, the account is waiting for activation by an admin.");
				}
				verifiedUser.save(db);
			}
			else if (out != null) out.println("{ \"error\":\"Invalid email verification hash!\" }");
			else msgs.add(MessageType.ERROR, "Invalid email verification hash!");
		}
		else msgs.add(MessageType.ERROR, "Invalid user id: "+request.getParameter("id"));

	}

}
