package io.wunderboss.ruby.rack;

import io.undertow.servlet.spec.HttpServletRequestImpl;
import io.undertow.servlet.spec.HttpServletResponseImpl;
import io.wunderboss.ruby.RuntimeHelper;
import org.jboss.logging.Logger;
import org.jruby.Ruby;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.builtin.IRubyObject;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RackServlet implements Servlet {
    public static final String RESPONSE_HANDLER_RB = "io/wunderboss/ruby/rack/response_handler";
    public static final String RESPONSE_HANDLER_CLASS_NAME = "WunderBoss::Rack::ResponseHandler";
    public static final String RESPONSE_HANDLER_METHOD_NAME = "handle";

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.rackApplication = (IRubyObject) config.getServletContext().getAttribute("rack_application");
        this.runtime = this.rackApplication.getRuntime();
        RuntimeHelper.requireUnlessDefined(this.runtime, RESPONSE_HANDLER_RB, RESPONSE_HANDLER_CLASS_NAME);
        this.responseModule = RuntimeHelper.getClass(this.runtime, RESPONSE_HANDLER_CLASS_NAME);
        try {
            this.rackEnvironment = new RackEnvironment(this.runtime);
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public final void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        if (request instanceof HttpServletRequestImpl && response instanceof HttpServletResponseImpl) {
            service((HttpServletRequestImpl) request, (HttpServletResponseImpl) response);
        }
    }

    public final void service(HttpServletRequestImpl request, HttpServletResponseImpl response) throws ServletException, IOException {
        if (((request.getPathInfo() == null) || (request.getPathInfo().equals("/"))) && !(request.getRequestURI().endsWith("/"))) {
            redirectToTrailingSlash(request, response);
            return;
        }

        RubyHash rackEnvHash = null;
        try {
            rackEnvHash = this.rackEnvironment.getEnv(request);
//            IRubyObject rackResponse = (IRubyObject) RuntimeHelper.call(this.runtime,
//                    this.rackApplication, "call", new Object[]{rackEnvHash});
//            RuntimeHelper.call(this.runtime, this.responseModule, RESPONSE_HANDLER_METHOD_NAME,
//                    new Object[]{rackResponse, response});
            IRubyObject rackResponse = this.rackApplication.callMethod(this.runtime.getCurrentContext(), "call", rackEnvHash);
            IRubyObject[] rubyObjects = new IRubyObject[2];
            rubyObjects[0] = rackResponse;
            rubyObjects[1] = JavaUtil.convertJavaToUsableRubyObject(this.runtime, response);
            this.responseModule.callMethod(this.runtime.getCurrentContext(), RESPONSE_HANDLER_METHOD_NAME, rubyObjects);
        } catch (RaiseException e) {
            throw new ServletException(e);
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            if (rackEnvHash != null) {
//                RubyIO input = (RubyIO) rackEnvHash.get("rack.input");
//                //explicitly close the inputstream, but leave the err stream open,
//                //as closing that detaches it from the log forever!
//                if (input != null && !input.isClosed()) {
//                    input.close();
//                }
            }
        }
    }

    private void redirectToTrailingSlash(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String redirectUri = request.getRequestURI() + "/";
        String queryString = request.getQueryString();
        if (queryString != null) {
            redirectUri = redirectUri + "?" + queryString;
        }
        redirectUri = response.encodeRedirectURL(redirectUri);
        response.sendRedirect(redirectUri);
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
    }

    private Ruby runtime;
    private IRubyObject rackApplication;
    private RubyModule responseModule;
    private RackEnvironment rackEnvironment;

    private static final Logger log = Logger.getLogger(RackServlet.class);

}

@@ -423,16 +423,53 @@
 bject;%0A%0A
+import javax.servlet.GenericServlet;%0A
 import j
@@ -482,32 +482,32 @@
 ervlet.Servlet;%0A
-
 import javax.ser
@@ -791,295 +791,32 @@
 let 
-implements Servlet %7B%0A    public static final String RESPONSE_HANDLER_RB = %22io/wunderboss/ruby/rack/response_handler%22;%0A    public static final String RESPONSE_HANDLER_CLASS_NAME = %22WunderBoss::Rack::ResponseHandler%22;%0A    public static final String RESPONSE_HANDLER_METHOD_NAME = %22handle%22;
+extends GenericServlet %7B
 %0A%0A  
@@ -888,32 +888,60 @@
 vletException %7B%0A
+        super.init(config);%0A
         this.rac
@@ -1446,32 +1446,32 @@
 etException(e);%0A
+
         %7D%0A    %7D%0A
@@ -1475,96 +1475,8 @@
  %7D%0A%0A
-    @Override%0A    public ServletConfig getServletConfig() %7B%0A        return null;%0A    %7D%0A%0A
     
@@ -4103,136 +4103,8 @@
  %7D%0A%0A
-    @Override%0A    public String getServletInfo() %7B%0A        return null;%0A    %7D%0A%0A    @Override%0A    public void destroy() %7B%0A    %7D%0A%0A
     
@@ -4251,16 +4251,284 @@
 nment;%0A%0A
+    public static final String RESPONSE_HANDLER_RB = %22io/wunderboss/ruby/rack/response_handler%22;%0A    public static final String RESPONSE_HANDLER_CLASS_NAME = %22WunderBoss::Rack::ResponseHandler%22;%0A    public static final String RESPONSE_HANDLER_METHOD_NAME = %22handle%22;%0A%0A
     priv

Clean up RackServlet a bit by extending GenericServlet