package demojsoncrud.servlets;

import demojsoncrud.utilities.PostRequest;
import java.io.IOException;
import java.io.PrintWriter;
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 org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@WebFilter("/*")
public class RequestFilter implements Filter, ServletContextListener {

  @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";

    if (String.valueOf(request.getRequestURL()).contains("http://localhost:8080/proyecto-estandar/")) {
      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(main) || url.contains(".jsp")) {
        chain.doFilter(request, response);
      } else {
        String auth = request.getHeader("Authorization");
        PostRequest postRequest = new PostRequest(urlRequested);
        respuesta = postRequest.getRespueta(auth);
        JSONObject valid = new JSONObject(respuesta);
        if (valid.getBoolean("status")) {
          chain.doFilter(request, response);
        } else {
            redirect(indexPath);
//            response.setStatus(response.SC_MOVED_TEMPORARILY);
//            response.setHeader("Location", indexPath);
//            response.sendRedirect(indexPath);
        }
      }
    } else {
      if (isAJAXRequest(request)) {
        StringBuilder sb = new StringBuilder();
        sb.append("");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        PrintWriter pw = response.getWriter();
        pw.println(sb.toString());
        pw.flush();
        return;
      }
      response.sendRedirect(indexPath);
    }
  }
  private void redirect (String indexPath){
      try {

	String url = indexPath;

	URL obj = new URL(url);
	HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
	conn.setReadTimeout(5000);
	conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
	conn.addRequestProperty("User-Agent", "Mozilla");
	conn.addRequestProperty("Referer", "google.com");

	System.out.println("Request URL ... " + url);

	boolean redirect = false;

	// normally, 3xx is redirect
	int status = conn.getResponseCode();
	if (status != HttpURLConnection.HTTP_OK) {
		if (status == HttpURLConnection.HTTP_MOVED_TEMP
			|| status == HttpURLConnection.HTTP_MOVED_PERM
				|| status == HttpURLConnection.HTTP_SEE_OTHER)
		redirect = true;
	}

	System.out.println("Response Code ... " + status);

	if (redirect) {

		// get redirect url from "location" header field
		String newUrl = conn.getHeaderField("Location");

		// get the cookie if need, for login
		String cookies = conn.getHeaderField("Set-Cookie");

		// open the new connnection again
		conn = (HttpURLConnection) new URL(newUrl).openConnection();
		conn.setRequestProperty("Cookie", cookies);
		conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
		conn.addRequestProperty("User-Agent", "Mozilla");
		conn.addRequestProperty("Referer", "google.com");
								
		System.out.println("Redirect to URL : " + newUrl);

	}

	BufferedReader in = new BufferedReader(
                              new InputStreamReader(conn.getInputStream()));
	String inputLine;
	StringBuffer html = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		html.append(inputLine);
	}
	in.close();

	System.out.println("URL Content... \n" + html.toString());
	System.out.println("Done");

    } catch (Exception e) {
	e.printStackTrace();
    }
  }
  private boolean isAJAXRequest(HttpServletRequest request) {
    boolean check = false;
    String facesRequest = request.getHeader("X-Requested-With");
    if (facesRequest != null && facesRequest.equals("XMLHttpRequest")) {
      check = true;
    }
    return check;
  }

  @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.
  }

}
