plugins {
    id('groovy')
}

repositories {
    google()
    mavenCentral()
    gradlePluginPortal()
}

dependencies {
    compileOnly(gradleApi())
    compileOnly(localGroovy())
    implementation(libs.guava)
    implementation(libs.androidGradleApi)
    implementation(libs.androidToolsCommon)
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(libs.versions.jvmToolchainMin.get()))
    }
}

task downloadAarDepsPlugin {
    final baseUrl = "https://raw.githubusercontent.com/robolectric/robolectric/robolectric-${libs.versions.robolectric.get()}/"
    final from = [
        "${baseUrl}buildSrc/src/main/groovy/org/robolectric/gradle/AarDepsPlugin.java",
        "${baseUrl}buildSrc/src/main/groovy/org/robolectric/gradle/agp/ExtractAarTransform.java",
        "${baseUrl}buildSrc/src/main/groovy/org/robolectric/gradle/agp/GenericTransformParameters.java",

    ]
    final groovySourceSet = sourceSets.named('main').get().allSource.sourceDirectories.find { it.name == 'groovy' } as File
    final to = [
        new File(groovySourceSet, '/org/robolectric/gradle/AarDepsPlugin.java'),
        new File(groovySourceSet, '/org/robolectric/gradle/agp/ExtractAarTransform.java'),
        new File(groovySourceSet, '/org/robolectric/gradle/agp/GenericTransformParameters.java'),
    ]


    inputs.property("from", from)
    outputs.files(to)

    doLast {
        from.indices.forEach { i ->
            final url = from[i]
            final targetFile = to[i]
            try {
                URI.create(url).toURL().withInputStream { inputStream -> targetFile.withOutputStream { it << inputStream } }
            } catch (IOException e) {
                logger.debug("Error during downloading ${url}. Keep the stored version.\n$e")
            }
        }
    }
}

tasks {
    compileJava.dependsOn(downloadAarDepsPlugin)
    compileGroovy.dependsOn(downloadAarDepsPlugin)
}
