/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package demojsoncrud.servlets;

import demojsoncrud.config.PathRequest;
import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONObject;

/**
 *
 * @author Percy Oliver Quispe Huarcaya
 */
public class RedireccionarServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String auth = request.getParameter("t");
        
        if (auth.contains("Bearer ")) {
            PostRequest sendPost = new PostRequest(PathRequest.ENVIAR_NUEVO_TOKEN);
            
            HttpSession session = request.getSession();
            
            String respuesta = sendPost.getRespueta(auth);//Crearia una sesion con el codigo usuario
            JSONObject getRespuesta = new JSONObject(respuesta);
            if(getRespuesta.getBoolean("status")){
                JSONObject obj = new JSONObject(respuesta);
                JSONObject menu = new JSONObject(obj.get("menu").toString());

                Cookie cookieAuth = new Cookie("Authorization", "Bearer "+obj.getString("token"));
                System.out.println("Menu de la cookie ;: "+menu.toString());

                cookieAuth.setMaxAge(36000);//10horas

                response.addCookie(cookieAuth);

                System.out.println("Redireccionar Servlet : Codigo Usuario ::: "+obj.getString("codigoUsuario"));
                session.setAttribute("codigo", obj.getString("codigoUsuario"));
                session.setAttribute("menu", menu.toString());
                session.setMaxInactiveInterval(120*60); //Tiempo en segundos
                request.getRequestDispatcher("/vistas/main.jsp").forward(request, response);
            }
        }
        Cookie cookieAuth = new Cookie("Authorization", "");
        cookieAuth.setMaxAge(0);
        response.addCookie(cookieAuth);
        request.getRequestDispatcher("/vistas/index.jsp").forward(request, response);
    }

}
