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 UserListController extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = (UserService) getServletContext().getAttribute("userService");

        if (userService == null) {
            throw new ServletException("failed userlist init");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession().getAttribute("user") == null) {
            resp.sendRedirect(getServletContext().getContextPath());
            return;
        }

        req.setAttribute("userlist", userService.getUserList());
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/userlist.jsp");
        dispatcher.forward(req, resp);
    }
}
