package demojsoncrud.servlets;

import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;

@WebFilter("/*")
public class RequestFilter implements Filter, ServletContextListener {
    private final String BASE = "http://localhost:8080/proyecto-estandar/";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String respuesta = "";
        String indexPath = "http://localhost:8080/proyecto-estandar/vistas/index.jsp";
        String index = "vistas/index.jsp";
        String urlRequested = "http://172.16.2.53:8080/security-rest/api/user/verificarLogin";
        System.out.println("URI "+request.getRequestURI());
        if (String.valueOf(request.getRequestURL()).contains(BASE)) {
            String login = request.getContextPath() + "/vistas/index.jsp";
            String main = request.getContextPath() + "/vistas/main.jsp";
            String plantilla = request.getContextPath() + "/plantilla";
            String js = request.getContextPath() + "/js";
            String url = String.valueOf(request.getRequestURL());
            
            if (url.contains(login) || url.contains(plantilla) || url.contains(js)|| url.contains("index.jsp")||url.contains("main.jsp")) {
                chain.doFilter(request, response);
            } else {
                JSONObject valid = null;
                String auth = "";
                if(url.contains(".jsp")){
                    auth = request.getHeader("Cookie");  
                    if(auth.contains("Bearer")){
                        String[] parts = auth.split(";");
                        String authorization = parts[0];
                        parts = authorization.split("%20");
                        auth = "Bearer "+parts[1];
                        System.out.println(auth);
                    }
                }else{
                    auth = request.getHeader("Authorization");  
                }
                PostRequest postRequest = new PostRequest(urlRequested);
                respuesta = postRequest.getRespueta(auth);
                valid = new JSONObject(respuesta);
                if (valid.getBoolean("status")) {
                    JSONObject menu=new JSONObject(valid.getString("menu"));//Obtiene el menu
                    JSONArray views = new JSONArray(menu.get("vistas").toString());//Obtiene las vistas disponibles del usuario
                    List<Object> salida=views.toList();
                    String ruta = request.getRequestURI();
                    int indice = obtenerIndex(ruta);
                    String rutaJsp = ruta.substring(indice, ruta.length());
                    if(url.contains(".jsp")){
                        boolean acceso = false;
                        for(Object vista :views){
                            System.out.println("Vista : "+vista +"rutaJSP : "+rutaJsp);
                            if(vista.toString().equalsIgnoreCase(rutaJsp)){
                                acceso=true;
                                break;
                            }
                        }
                        if(!acceso){
                            Response.ResponseBuilder builder = null;
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            response.sendError(401);
                            builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
                            throw new WebApplicationException(builder.build());
                        }
                    }
//                    List<String> views = (List<String>) ;
                    chain.doFilter(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.sendError(401);
                }
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.sendError(401);
        }
    }
    private int obtenerIndex(String ruta){
        char[] c = ruta.toCharArray();
        int salida = 0;
        for (int i = c.length-1; i >= 0; i--) {
            String help = c[i]+"";
            if(!help.equals("/")){
                salida = i;
            }else{
                break;
            }
        }
        
        return salida;
    }
    @Override
    public void destroy() {

    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}