package io.quarkus.gradle.nativeimage;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

import org.junit.jupiter.api.Test;

import io.quarkus.gradle.BuildResult;
import io.quarkus.test.devmode.util.DevModeTestUtils;

public class BasicJavaNativeBuildIT extends QuarkusNativeGradleITBase {

    @Test
    public void shouldBuildNativeImage() throws Exception {
        final File projectDir = getProjectDir("basic-java-native-module");

        final BuildResult build = runGradleWrapper(projectDir, "clean", "quarkusBuild", "-Dquarkus.package.type=native");

        assertThat(build.getTasks().get(":quarkusBuild")).isEqualTo(BuildResult.SUCCESS_OUTCOME);
        final String buildOutput = build.getOutput();
        // make sure the output log during the build contains some expected logs from the native-image process
        assertThat(buildOutput)
                .withFailMessage("native-image build log is missing certain expected log messages: \n\n %s", buildOutput)
                .contains("(clinit):", "(typeflow):", "[total]:");
        Path nativeImagePath = projectDir.toPath().resolve("build").resolve("foo-1.0.0-SNAPSHOT-runner");
        assertThat(nativeImagePath).exists();
        Process nativeImageProcess = runNativeImage(nativeImagePath.toAbsolutePath().toString());
        try {
            final String response = DevModeTestUtils.getHttpResponse("/hello");
            assertThat(response)
                    .withFailMessage("Response %s for /hello was expected to contain the hello, but didn't", response)
                    .contains("hello");
        } finally {
            nativeImageProcess.destroy();
        }

    }

    private Process runNativeImage(String nativeImage) throws IOException {
        final ProcessBuilder processBuilder = new ProcessBuilder(nativeImage);
        processBuilder.inheritIO();
        return processBuilder.start();
    }
}

@@ -371,16 +371,97 @@
 Base %7B%0A%0A
+    public static final String NATIVE_IMAGE_NAME = %22foo-1.0.0-SNAPSHOT-runner%22;%0A%0A
     @Tes
@@ -984,16 +984,452 @@
 process%0A
+        CharSequence%5B%5D expectedOutput;%0A        if (buildOutput.contains(%22Version info:%22)) %7B // Starting with 22.0 the native-image output changed%0A            expectedOutput = new CharSequence%5B%5D %7B %22Initializing...%22, %22Performing analysis...%22,%0A                    %22Finished generating '%22 + NATIVE_IMAGE_NAME + %22' in%22 %7D;%0A        %7D else %7B%0A            expectedOutput = new CharSequence%5B%5D %7B %22(clinit):%22, %22(typeflow):%22, %22%5Btotal%5D:%22 %7D;%0A        %7D%0A
         
@@ -1604,46 +1604,22 @@
 ins(
-%22(clinit):%22, %22(typeflow):%22, %22%5Btotal%5D:%22
+expectedOutput
 );%0A 
@@ -1697,35 +1697,25 @@
 lve(
-%22foo-1.0.0-SNAPSHOT-runner%22
+NATIVE_IMAGE_NAME
 );%0A 

Fix gradle integration test to work with GraalVM >= 22.0