package org.academiadecodigo.enuminatti.helloworld;

import org.academiadecodigo.enuminatti.helloworld.models.User;

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;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;

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

public class HelloWorld extends HttpServlet {

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

        if (name == null || name.isEmpty()) {
            throw new ServletException("quem és tu mesmo?");
        }

        if (name.equalsIgnoreCase("pilas")) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "pára de usar essa merda pa testar");
            return;
        }

        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        User user = new User("Ricardo", "c@d", "a");
        user.setName(name);

//        getServletContext().setAttribute("user", user);
//        req.getSession().setAttribute("user", user);
        req.setAttribute("user", user);

        RequestDispatcher page1Dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
        page1Dispatcher.forward(req, resp);
        RequestDispatcher footerDispatcher = getServletContext().getRequestDispatcher("/foot.jsp");

        resp.getWriter().println("<p>");
        for (String k : req.getParameterMap().keySet()) {
            resp.getWriter().println(k + ": " + Arrays.asList(req.getParameterMap().get(k)));
        }
        resp.getWriter().println("</p>");

        footerDispatcher.include(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("username");
        String password = req.getParameter("password");
        resp.getWriter().println(name + " " + password + " " + new HashMap<>(req.getParameterMap()).toString());
        if (name != null && password != null) {
            resp.setContentType("text/html");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            String helloHtml = "<html style=\"background:black; color: gray\">" +
                    String.format("<body><h1>sup %s %s</h1></body></html>", name, password);
            out.println(helloHtml);
        }
    }
}
