package com.mockobjects.examples.password;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ForgotPasswordServlet extends HttpServlet {
    public static final String SENT_PARAM_NAME = "sent";
    public static final String EMAIL_FAILED_PARAM_NAME = "bademail";
    public static final String EMAIL_NOT_FOUND_PARAM_NAME = "noemail";
    public static final String EMAIL_PARAM = "email";

    private PasswordReminder passwordReminder;

    public ForgotPasswordServlet(PasswordReminder aPasswordReminder) {
        super();
        passwordReminder = aPasswordReminder;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String emailAddress = request.getParameter(EMAIL_PARAM);

        try {
            passwordReminder.sendReminder(emailAddress);
            redirectFor(response, emailAddress);
        } catch (NotFoundException e) {
            throw new ServletException("Password not found", e);
        }
    }

    private void redirectFor(HttpServletResponse response, String emailAddress) throws IOException {
        response.sendRedirect("sent_uri?" + EMAIL_PARAM + "=" + emailAddress);
    }

}
