package org.academiadecodigo.enuminatti.helloworld.controllers;

import org.academiadecodigo.enuminatti.helloworld.models.Bootcamp;
import org.academiadecodigo.enuminatti.helloworld.models.User;
import org.academiadecodigo.enuminatti.helloworld.services.BootcampService;
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 BootcampListController extends HttpServlet {

    private BootcampService bootcampService;

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

        if (bootcampService == null) {
            throw new ServletException("failed bootcamplist 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("bootcamplist", bootcampService.getBootcampList());
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/bootcamplist.jsp");
        dispatcher.forward(req, resp);
    }
}
