package zall.page;

import zall.Zallery;
import zall.ZalleryServlet;
import zall.bean.User;
import zall.manager.EmailManager;
import zutil.ObjectUtil;
import zutil.db.DBConnection;
import zutil.log.LogUtil;
import zutil.ui.UserMessageManager;
import zutil.ui.UserMessageManager.MessageLevel;
import zutil.ui.UserMessageManager.UserMessage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Logger;

@WebServlet(RegisterServlet.URI)
public class RegisterServlet extends ZalleryServlet {
    private static Logger logger = LogUtil.getLogger();

    public static final String URI = "/register";
    private static final String JSP_FILE = "page_register.jsp";

    private static final String INPUT_ID_FIRST_NAME = "first-name";
    private static final String INPUT_ID_LAST_NAME = "last-name";
    private static final String INPUT_ID_EMAIL = "email";
    private static final String INPUT_ID_PASSWORD = "password";
    private static final String INPUT_ID_PASSWORD_REPEATE = "password-re";


    public void doGet(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws ServletException, IOException, SQLException {
        UserMessageManager msgs = Zallery.getUserMessage(request.getSession());

        // Verify email address
        String verifyEmailHash = request.getParameter("verifyemail");
        if (!ObjectUtil.isEmpty(verifyEmailHash)) {
            User verfUser = User.load(db, Long.parseLong(request.getParameter("id")));
            if (verfUser != null) {
                if (verfUser.verifyEmail(request.getParameter("hash"))) {
                    EmailManager.sendNewUserRegistrationToAdmin(verfUser, db);
                    verfUser.save(db);
                    msgs.add(new UserMessage(MessageLevel.SUCCESS, lang.getString("email.verification.success")));
                    msgs.add(new UserMessage(MessageLevel.WARNING, lang.getString("user.disabled")));
                } else {
                    logger.severe("Email verification failed, incorrect hash " + verfUser.getEmail() +
                            "(user) " + request.getParameter("hash") + " = (server) " + verfUser.generateEmailVerificationHash());
                    msgs.add(new UserMessage(MessageLevel.ERROR, "Email verification failed."));
                }
            } else {
                logger.severe("Email verification failed, unknown user: " + request.getParameter("id"));
                msgs.add(new UserMessage(MessageLevel.ERROR, "Email verification failed."));
            }
        }

        include(JSP_FILE, request, response);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws SQLException, IOException, ServletException {
        UserMessageManager msgs = Zallery.getUserMessage(request.getSession());

        /*
         * Check inputs
         */

        String firstName = (String) request.getAttribute(INPUT_ID_FIRST_NAME);
        String lastName = (String) request.getAttribute(INPUT_ID_LAST_NAME);
        String email = (String) request.getAttribute(INPUT_ID_EMAIL);
        String password = (String) request.getAttribute(INPUT_ID_PASSWORD);
        String passwordRe = (String) request.getAttribute(INPUT_ID_PASSWORD_REPEATE);

        if (firstName == null)
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.not.found.first.name")));
        if (lastName == null)
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.not.found.last.name")));
        if (email == null)
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.not.found.email")));
        if (password == null)
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.not.found.password")));
        if (passwordRe == null)
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.not.found.password")));
        else if (passwordRe.equals(password))
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.incorrect.password.match")));

        if (User.load(db, (String) request.getAttribute(INPUT_ID_EMAIL)) != null) {
            msgs.add(new UserMessage(MessageLevel.ERROR, lang.getString("parameter.email.exists")));
            return;
        }

        /*
         * Create new user
         */

        User user = new User();
        user.setName(firstName + " " + lastName);
        user.setEmail(email);
        user.setPassword(password);
        user.save(db);
        EmailManager.sendVerificationEmail(user);
        request.getSession().setAttribute("user", user);
        logger.info("Registered new user: " + user.getName() + ".");
        msgs.add(new UserMessage(MessageLevel.INFO,
                lang.getString("account.created") + " " + lang.getString("email.verification.sent")));

        forward("/login", request, response);
    }
}
