/*
 * 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;

/**
 *
 * @author sistem08user
 */
public class LogOut extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String auth = request.getHeader("Cookie"); 
        
        if (auth.contains("Bearer")) {
            int indiceBearer = 0;
            int indiceToken = 0;
            Cookie cookieAuth=null;
            Cookie cookieMenu=null;
            PostRequest postRequest = new PostRequest(PathRequest.LOG_OUT);
            String respuesta = "";
            String[] parts = auth.split(";");
            for (int i = 0; i < parts.length - 1; i++) {
                if (parts[i].contains("Bearer")) {
                    indiceBearer = i;
                    break;
                }
            }
            String authorization = parts[indiceBearer];
            if (authorization.contains("%20")) {
                parts = authorization.split("%20");
            } else if (authorization.contains(" ")) {
                parts = authorization.split(" ");
            }
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].startsWith("ey")) {//El token empieza 
                    indiceToken = i;
                    break;
                }
            }
            auth = "Bearer " + parts[indiceToken];
            respuesta = postRequest.getRespueta(auth.replaceAll("\"", ""));
            cookieAuth = new Cookie("Authorization", "");
            cookieMenu = new Cookie("menu", "");
            cookieAuth.setMaxAge(0);
            cookieMenu.setMaxAge(0);
            response.addCookie(cookieAuth);
            response.addCookie(cookieMenu);
            request.getSession().removeAttribute("codigo");//
            request.getRequestDispatcher("/vistas/login.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("/vistas/login.jsp").forward(request, response);
        }
    }
    
}
