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.action.ZalleryAction;
import zall.bean.User;
import zall.manager.EmailManager;
import zutil.db.DBConnection;
import zutil.ui.UserMessageManager;
import zutil.ui.UserMessageManager.MessageLevel;
import zutil.ui.UserMessageManager.UserMessage;

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, UserMessageManager 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())
                    msgs.add(new UserMessage(MessageLevel.INFO, "Your email has been successfully verified"));
                else {
                    EmailManager.sendNewUserRegistrationToAdmin(verifiedUser, db);
                    msgs.add(new UserMessage(MessageLevel.INFO, "Your email has been successfully verified, the account is waiting for activation by an admin."));
                }
                verifiedUser.save(db);
            } else
                msgs.add(new UserMessage(MessageLevel.ERROR, "Invalid email verification hash!"));
        } else
            msgs.add(new UserMessage(MessageLevel.ERROR, "Invalid user id: " + request.getParameter("id")));

    }

}
