package zall.page;

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

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


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

    public  static final String URI = "/login";
    private static final String JSP_FILE = "page_login.jsp";

    private static final String FORM_EMAIL = "email";
    private static final String FORM_PASSWORD = "password";


    public void doGet(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws ServletException, IOException, SQLException {
        // User already logged in?
        User user = AuthenticationManager.getUserSession(request.getSession());

        // Authenticate with cookies
        if (user == null)
            user = AuthenticationManager.authenticate(db, request, response);

        // Forward user
        if (user != null) {
            logger.fine("User(" + user.getEmail() + ") already authenticated, forwarding to gallery.");
            redirect(GalleryServlet.URI, request, response);
        } else {
            include(JSP_FILE, request, response);
        }
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response, DBConnection db) throws SQLException, ServletException, IOException {
        UserMessageManager msgs = Zallery.getUserMessage(request.getSession());
        User user = AuthenticationManager.authenticate(db,
                request.getParameter(FORM_EMAIL),
                request.getParameter(FORM_PASSWORD),
                request, response);

        // Successful login
        if (user != null) {
            logger.fine("Authenticated user(" + user.getEmail() + ") successfully, forwarding to gallery.");
            redirect(GalleryServlet.URI, request, response);
        }
        // Failed login
        else {
            msgs.add(new UserMessageManager.UserMessage(MessageLevel.ERROR, lang.getString("incorrect.user_or_pass")));
            doGet(request, response, db);
        }
    }
}
