import org.robolectric.gradle.AarDepsPlugin

plugins {
    alias(libs.plugins.kotlinJvm)
    alias(libs.plugins.kotlinxKover)
    alias(libs.plugins.detekt)
    alias(libs.plugins.dokka)
    alias(libs.plugins.robolectricExtensionGradlePlugin)
    id('maven-publish')
}

apply plugin: AarDepsPlugin

configurations.configureEach { configuration ->
    configuration.exclude(group: 'androidx.tracing', module: 'tracing')
    configuration.exclude(group: 'androidx.annotation', module: 'annotation-experimental')
}

kotlin {
    jvmToolchain(libs.versions.jvmToolchainMin.get().toInteger())
}

robolectricJUnitJupiter {
    doNotAddDependencies = true
}

test {
    testLogging {
        showStandardStreams = true
        showExceptions = true
        showCauses = true
        showStackTraces = true
    }
    systemProperty 'junit.jupiter.execution.parallel.enabled', 'true'
    systemProperty 'junit.jupiter.execution.parallel.mode.default', 'same_thread'
    systemProperty 'junit.jupiter.execution.parallel.mode.classes.default', 'same_thread'
    systemProperty 'java.util.logging.config.file',
        "${projectDir}/src/test/resources/logging.properties"
    systemProperty 'robolectric.usePreinstrumentedJars', 'true'
}

tasks.test {
    javaLauncher.set(
        javaToolchains.launcherFor {
            languageVersion.set(JavaLanguageVersion.of(libs.versions.jvmToolchain.get().toInteger()))
        }
    )
}

detekt {
    toolVersion = libs.versions.detekt.get()
    autoCorrect true
}

dependencies {
    detektPlugins(libs.detektFormatting)
    detektPlugins(libs.detektRulesLibraries)
    api(libs.robolectric)
    implementation(libs.junit4)
    implementation(platform(libs.junit5Bom))
    api(libs.junit5JupiterApi)
    implementation(libs.junit5PlatformLauncher)
    implementation(libs.guavaConstraint) {
        because 'CVE-2023-2976 7.1 Transitive Files or Directories Accessible to External Parties' +
            ' vulnerability with High severity found'
    }
    implementation(libs.kotlinReflect)
    testImplementation(libs.robolectricAndroidAllJava11)
    testImplementation(libs.junit4)
    testImplementation(libs.androidxTestExtJunit)
    testImplementation(libs.kotlinTestJUnit5)
    testImplementation(libs.junit5JupiterParams)
    testRuntimeOnly(libs.junit5JupiterEngine)
}

private void bashExecute(String command) {
    final process = command.execute()
    final error = process.errorReader().readLines().join("\n")
    if (!error.isBlank()) {
        logger.error("error during execution of:\ncommand:$command\ndetails:\n$error")
    }
}

tasks.register('generateAndroidR') {
    final androidHome = System.getenv("ANDROID_HOME")
    final aapt = "$androidHome/build-tools/${libs.versions.androidBuildTools.get()}/aapt"
    final testSourceSet = sourceSets.named('test').get()
    final testJavaSourceDir = testSourceSet.allSource.sourceDirectories.find { it.name == 'java' } as File
    final testResourcesDir = testSourceSet.allSource.sourceDirectories.find { it.name == 'resources' } as File
    final androidResDir = new File(testResourcesDir, 'res')
    final androidAssetsDir = new File(testResourcesDir, 'assets')
    final outputResourcesFile = new File(testResourcesDir, 'resources.ap_')
    final androidJarFile = "$androidHome/platforms/android-${libs.versions.androidCompileSdk.get()}/android.jar"
    final androidManifestFile = new File(testResourcesDir.parentFile, 'AndroidManifest.xml')

    inputs.dir(androidResDir)
    inputs.dir(androidAssetsDir)
    inputs.file(androidManifestFile)

    outputs.file(outputResourcesFile)
    outputs.dir(testJavaSourceDir)
    doLast {
        final aaptCommand = "$aapt p -v -f -m --auto-add-overlay -I $androidJarFile " +
            "-S $androidResDir " +
            "-M $androidManifestFile.path " +
            "-A $androidAssetsDir.path " +
            "-F $outputResourcesFile.path " +
            "-J $testJavaSourceDir.path " +
            "--no-version-vectors"
        bashExecute(aaptCommand)
    }
}

apply from: "${rootProject.layout.projectDirectory.file('gradle/dokka.gradle')}"
apply from: "${rootProject.layout.projectDirectory.file('gradle/pom.gradle')}"

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            artifact(kotlinSourcesJar)
            artifact(dokkaJavadocJar)

            setupPom(it, 'JUnit5 Robolectric Extension')
        }
    }
}

apply from: "${rootProject.layout.projectDirectory.file('gradle/setupMavenCentralForPublishing.gradle')}"
apply from: "${rootProject.layout.projectDirectory.file('gradle/signing.gradle')}"
