package org.academiadecodigo.enuminatti.helloworld.controllers;

import org.academiadecodigo.enuminatti.helloworld.services.UserService;

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

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class LoginController extends HttpServlet {

    private UserService userService;
    private RequestDispatcher dispatcher;

    public LoginController() {
    }

    @Override
    public void init() throws ServletException {
        userService = (UserService) getServletContext().getAttribute("userService");
        dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");

        if (userService == null || dispatcher == null) {
            throw new ServletException("failed login init");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        dispatcher.forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        if (name == null || password == null || name.isEmpty() || password.isEmpty()) {
            resp.sendRedirect(getServletContext().getContextPath());
            return;
        }

        if (userService.authenticate(name, password)) {
            req.getSession().setAttribute("user", name);
            resp.sendRedirect(getServletContext().getContextPath() + "/bootcamps");
            return;
        }

        dispatcher.forward(req, resp);
    }

}
