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

public class ModifyUserStatusAction extends ZalleryAction {

    public ModifyUserStatusAction() {
        super("moduser", true);
    }

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

        User target_user = null;
        if (request.getParameter("id") != null)
            target_user = User.load(db, Long.parseLong(request.getParameter("id")));
        else // set target user to the logged in user
            target_user = user;

        if (AuthenticationManager.canEdit(user, target_user)) {
            if (request.getParameter("email") != null)
                target_user.setEmail(request.getParameter("email"));
            if (request.getParameter("password") != null) {
                if (target_user.getPasswordHash() == null)
                    target_user.setPassword(request.getParameter("password"));
                else if (request.getParameter("oldPassword") != null)
                    if (target_user.getPasswordHash().equals(request.getParameter("oldPassword")))
                        target_user.setPassword(request.getParameter("password"));
                    else {
                        msgs.add(new UserMessage(MessageLevel.ERROR, "Wrong password!"));
                        return;
                    }
            }
            if (request.getParameter("name") != null)
                target_user.setName(request.getParameter("name"));
            target_user.save(db);
            if (!user.isEmailVerified())
                EmailManager.sendVerificationEmail(target_user);
            msgs.add(new UserMessage(MessageLevel.INFO, "Settings saved successfully."));
        } else
            msgs.add(new UserMessage(MessageLevel.ERROR, "You are not authorize to change these values!"));
    }

}
