package nu.studer.gradle.jooq;

import nu.studer.gradle.jooq.util.Gradles;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.jvm.toolchain.JavaLauncher;
import org.gradle.jvm.toolchain.JavaToolchainService;
import org.gradle.jvm.toolchain.JavaToolchainSpec;
import org.gradle.process.JavaExecSpec;

/**
 * Isolates Gradle toolchain related types, introduced in 6.7 and above.
 */
abstract class ToolchainHelper {

    private static final String GRADLE_VERSION_WITH_TOOLCHAIN = "7.3";

    static void tryConfigureJavaLauncher(Property<Object> launcher, ExtensionContainer extensions) {
        if (Gradles.isAtLeastGradleVersion(GRADLE_VERSION_WITH_TOOLCHAIN)) {
            JavaToolchainSpec toolchain = extensions.getByType(JavaPluginExtension.class).getToolchain();
            JavaToolchainService service = extensions.getByType(JavaToolchainService.class);
            Provider<JavaLauncher> defaultLauncher = service.launcherFor(toolchain);
            launcher.convention(defaultLauncher);
        }
    }

    static void tryApplyJavaLauncher(Property<Object> launcher, JavaExecSpec spec) {
        if (Gradles.isAtLeastGradleVersion(GRADLE_VERSION_WITH_TOOLCHAIN) && launcher.isPresent() && launcher.get() instanceof JavaLauncher) {
            spec.setExecutable(((JavaLauncher) launcher.get()).getExecutablePath().getAsFile().getAbsolutePath());
        } else if (!Gradles.isAtLeastGradleVersion(GRADLE_VERSION_WITH_TOOLCHAIN) && launcher.isPresent()) {
            throw new IllegalArgumentException("Toolchain support requires Gradle " + GRADLE_VERSION_WITH_TOOLCHAIN);
        }
    }

    private ToolchainHelper() {
    }

}

@@ -590,35 +590,23 @@
  String 
-GRADLE_VERSION_WITH
+INITIAL
 _TOOLCHA
@@ -611,15 +611,23 @@
 HAIN
+_SUPPORT
  = %22
-7.3
+6.7
 %22;%0A%0A
@@ -770,35 +770,23 @@
 Version(
-GRADLE_VERSION_WITH
+INITIAL
 _TOOLCHA
@@ -787,16 +787,24 @@
 OOLCHAIN
+_SUPPORT
 )) %7B%0A   
@@ -1279,35 +1279,23 @@
 Version(
-GRADLE_VERSION_WITH
+INITIAL
 _TOOLCHA
@@ -1288,32 +1288,40 @@
 NITIAL_TOOLCHAIN
+_SUPPORT
 ) && launcher.is
@@ -1541,35 +1541,23 @@
 Version(
-GRADLE_VERSION_WITH
+INITIAL
 _TOOLCHA
@@ -1558,16 +1558,24 @@
 OOLCHAIN
+_SUPPORT
 ) && lau
@@ -1685,27 +1685,15 @@
 %22 + 
-GRADLE_VERSION_WITH
+INITIAL
 _TOO
@@ -1698,16 +1698,24 @@
 OOLCHAIN
+_SUPPORT
 );%0A     

Allow toolchain configuration as of Gradle 6.7