package com.proofpoint.jetty;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.RequestType;
import com.ning.http.client.Response;
import com.ning.http.util.Base64;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.server.Server;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;

import static org.testng.Assert.assertEquals;

public class TestJettyProvider
{
    private Server server;

    @AfterMethod
    public void teardown()
            throws Exception
    {
        if (server != null) {
            server.stop();
        }
    }

    @Test
    public void testHttp()
            throws Exception
    {
        // TODO: replace with NetUtils.findUnusedPort()
        ServerSocket socket = new ServerSocket();
        socket.bind(new InetSocketAddress(0));
        final int port = socket.getLocalPort();
        socket.close();

        final JettyConfig config = new JettyConfig()
        {
            @Override
            public int getHttpPort()
            {
                return port;
            }
        };

        createServer(config);
        server.start();

        AsyncHttpClient client = new AsyncHttpClient();
        Response response = client.prepareGet("http://localhost:" + port + "/")
                .execute()
                .get();

        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
    }

    public void testHttps()
    {
        // TODO
    }

    @Test
    public void testAuth()
            throws Exception
    {
        // TODO: replace with NetUtils.findUnusedPort()
        ServerSocket socket = new ServerSocket();
        socket.bind(new InetSocketAddress(0));
        final int port = socket.getLocalPort();
        socket.close();

        final File file = File.createTempFile("auth", ".properties");
        PrintStream out = new PrintStream(new FileOutputStream(file));
        out.print("user: password");
        out.close();

        final JettyConfig config = new JettyConfig()
        {
            @Override
            public int getHttpPort()
            {
                return port;
            }

            @Override
            public String getUserAuthPath()
            {
                return file.getAbsolutePath();
            }
        };

        createServer(config);
        server.start();

        AsyncHttpClient client = new AsyncHttpClient();
        Response response = client.prepareGet("http://localhost:" + port + "/")
                .addHeader("Authorization", "Basic " + Base64.encode("user:password".getBytes()))
                .execute()
                .get();

        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
        assertEquals(response.getResponseBody(), "user");
    }

    public void testJMX()
    {
        // TODO
    }

    public void testStats()
    {
        // TODO
    }

    public void testGzipRequest()
    {
        // TODO
    }

    public void testGzipResponse()
    {
        // TODO
    }

    public void testLogPathIsNotDirectory()
    {
        // TODO
    }

    private void createServer(final JettyConfig config)
    {
        server = Guice.createInjector(new ServletModule()
        {
            @Override
            protected void configureServlets()
            {
                serve("/*").with(DummyServlet.class);
            }
        }, new Module()
        {
            @Override
            public void configure(Binder binder)
            {
                binder.bind(DummyServlet.class).in(Scopes.SINGLETON);
                binder.bind(Server.class).toProvider(JettyProvider.class);
                binder.bind(JettyConfig.class).toInstance(config);
                binder.bind(LoginService.class).toProvider(HashLoginServiceProvider.class);
            }
        }).getInstance(Server.class);
    }

    private static class DummyServlet
        extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException
        {
            resp.setStatus(HttpServletResponse.SC_OK);
            if (req.getUserPrincipal() != null) {
                resp.getOutputStream().write(req.getUserPrincipal().getName().getBytes());
            }
        }
    }
}

@@ -24,16 +24,51 @@
 jetty;%0A%0A
+import com.google.common.io.Files;%0A
 import c
@@ -554,24 +554,50 @@
 ver.Server;%0A
+import org.testng.Assert;%0A
 import org.t
@@ -627,16 +627,60 @@
 Method;%0A
+import org.testng.annotations.BeforeMethod;%0A
 import o
@@ -1162,16 +1162,324 @@
 server;%0A
+    private File tempDir;%0A%0A    @BeforeMethod%0A    public void setup()%0A            throws IOException%0A    %7B%0A        tempDir = Files.createTempDir()%0A                .getCanonicalFile(); // getCanonicalFile needed to get around Issue 365 (http://code.google.com/p/guava-libraries/issues/detail?id=365)%0A    %7D%0A    
 %0A    @Af
@@ -1612,24 +1612,67 @@
 );%0A        %7D
+%0A%0A        Files.deleteRecursively(tempDir);
 %0A    %7D%0A%0A    
@@ -2135,32 +2135,195 @@
 t;%0A            %7D
+%0A%0A            @Override%0A            public String getLogPath()%0A            %7B%0A                return new File(tempDir, %22jetty.log%22).getAbsolutePath();%0A            %7D
 %0A        %7D;%0A%0A   
@@ -3066,16 +3066,25 @@
 perties%22
+, tempDir
 );%0A     
@@ -3145,24 +3145,42 @@
 eam(file));%0A
+        try %7B%0A    
         out.
@@ -3200,24 +3200,68 @@
 password%22);%0A
+        %7D%0A        catch (Exception e) %7B%0A    
         out.
@@ -3260,32 +3260,42 @@
     out.close();
+%0A        %7D
 %0A%0A        final 
@@ -4369,17 +4369,92 @@
 sNot
-Directory
+File()%0A    %7B%0A        // TODO%0A    %7D%0A%0A    public void testLogPathParentCannotbeCreated
 ()%0A 

use temp dir for jetty test