/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2018 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.undertow.server.handlers.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.GZIPOutputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.DecompressingEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import io.undertow.server.handlers.CanonicalPathHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.resource.PathResourceManager;
import io.undertow.server.handlers.resource.PreCompressedResourceSupplier;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.testutils.DefaultServer;
import io.undertow.testutils.HttpClientUtils;
import io.undertow.testutils.TestHttpClient;
import io.undertow.httpcore.HttpHeaderNames;
import io.undertow.httpcore.StatusCodes;

/**
 * @author Stuart Douglas
 */
@RunWith(DefaultServer.class)
public class PreCompressedResourceTestCase {

    @After
    public void clean() throws IOException, URISyntaxException {
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        if (Files.exists(rootPath.resolve("page.html.gz"))) {
            Files.delete(rootPath.resolve("page.html.gz"));
        }

        if (Files.exists(rootPath.resolve("page.html.gzip"))) {
            Files.delete(rootPath.resolve("page.html.gzip"));
        }

        if (Files.exists(rootPath.resolve("page.html.nonsense"))) {
            Files.delete(rootPath.resolve("page.html.nonsense"));
        }

        if (Files.exists(rootPath.resolve("page.html.gzip.nonsense"))) {
            Files.delete(rootPath.resolve("page.html.gzip.nonsense"));
        }
    }

    @Test
    public void testContentEncodedResource() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path", new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gz"))
                                    .setDirectoryListingEnabled(true))));

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response, that doesn't exists, so returns plain
            assertResponse(compClient.execute(get), false, plainResponse);

            //generate compressed resource with extension .gz
            generatePreCompressedResource("gz");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gz");

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    @Test
    @Ignore("UT3 - P4")
    public void testCorrectResourceSelected() throws IOException, URISyntaxException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/page.html");
        TestHttpClient client = new TestHttpClient();
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

        try (CloseableHttpClient compClient = HttpClientBuilder.create().build()){
            DefaultServer.setRootHandler(new CanonicalPathHandler()
                    .setNext(new PathHandler()
                            .addPrefixPath("/path",new ResourceHandler(new PreCompressedResourceSupplier(new PathResourceManager(rootPath, 10485760)).addEncoding("gzip", ".gzip"))
                                            .setDirectoryListingEnabled(true)))
                    );

            //assert response without compression
            final String plainResponse = assertResponse(client.execute(get), false);

            //assert compressed response generated by filter
            assertResponse(compClient.execute(get), true, plainResponse);

            //generate resources
            generatePreCompressedResource("gzip");
            generatePreCompressedResource("nonsense");
            generatePreCompressedResource("gzip.nonsense");

            //assert compressed response that was pre compressed
            assertResponse(compClient.execute(get), true, plainResponse, "gzip");

        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    private void generateGZipFile(Path source, Path target) throws IOException {
        byte[] buffer = new byte[1024];

        GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(target.toFile()));
        FileInputStream in = new FileInputStream(source.toFile());

        int len;
        while ((len = in.read(buffer)) > 0) {
            gzos.write(buffer, 0, len);
        }

        in.close();
        gzos.finish();
        gzos.close();
    }

    private void replaceStringInFile(Path file, String original, String replacement) throws IOException {
        String content = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
        content = content.replaceAll(original, replacement);
        Files.write(file, content.getBytes(StandardCharsets.UTF_8));
    }

    private String assertResponse(HttpResponse response, boolean encoding) throws IOException {
        return assertResponse(response, encoding, null, null);
    }

    private String assertResponse(HttpResponse response, boolean encoding, String compareWith) throws IOException {
        return assertResponse(response, encoding, compareWith, "web");
    }

    /**
     * Series of assertions checking response code, headers and response content
     */
    private String assertResponse(HttpResponse response, boolean encoding, String compareWith, String extension) throws IOException {
        Assert.assertEquals(StatusCodes.OK, response.getStatusLine().getStatusCode());
        String body = HttpClientUtils.readResponse(response);
        Header[] headers = response.getHeaders(HttpHeaderNames.CONTENT_TYPE);
        Assert.assertEquals("text/html", headers[0].getValue());

        if (encoding) {
            assert response.getEntity() instanceof DecompressingEntity; //no other nice way to be sure we get back gzipped content
        } else {
            Assert.assertNull(response.getFirstHeader(HttpHeaderNames.CONTENT_ENCODING));
        }

        if (compareWith != null) {
            Assert.assertEquals(compareWith.replace("\r", "").replace("web", extension), body.replace("\r", "")); //ignore line ending differences and change inside of html page
        }
        return body;
    }

    /**
     * Creates compressed resource made by compressing page.html which content is updated before with {@param extension}
     * and after compression returned to original content
     */
    private void generatePreCompressedResource(String extension) throws IOException, URISyntaxException{
        Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
        Path html = rootPath.resolve("page.html");

        replaceStringInFile(html, "web", extension);
        generateGZipFile(html, rootPath.resolve("page.html." + extension));
        replaceStringInFile(html, extension, "web");
    }
}