import org.gradle.api.execution.TaskExecutionGraph

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/5.0/userguide/tutorial_java_projects.html
 */

plugins {
    // Apply the java plugin to add support for Java
    // java
    `java-library`

    // Apply the application plugin to add support for building an application
    // application
}

repositories {
    mavenLocal()
    mavenCentral()

    // Use jcenter for resolving your dependenes.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

dependencies {
    // TODO

    api("org.xmlresolver", "xmlresolver", "1.1.0")
    api("net.sf.saxon", "Saxon-HE", "10.3")

    // Use TestNG framework, also requires calling test.useTestNG() below
    testImplementation("org.testng:testng:7.3.0")
}

ant.importBuild("build.xml")

val jars = task("jars") {
    inputs.files(fileTree("**/*.java"))
    outputs.files("build/jing.jar", "build/trang.jar", "build/dtdinst.jar")

    // val antJar = tasks.named("ant-jar").outputs.upToDateWhen(outputs.upToDate)

    finalizedBy(":ant-jar")
}

// https://stackoverflow.com/questions/41794914/how-to-create-the-fat-jar-with-gradle-kotlin-script
val jingTrang = task("jingtrang", Jar::class) {
    from(listOf("build/jing.jar", "build/trang.jar").map { it -> zipTree(it) })
    with(tasks.jar.get() as CopySpec)
    dependsOn(":ant-jar")
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE;
}

// if jing-trang is a composite, merged jar resolution
// does not work, even if the artifact is declared like below
artifacts {
    add("archives", jingTrang)
    add("default", jingTrang)
}

// https://docs.gradle.org/current/userguide/kotlin_dsl.html#using_the_container_api
tasks.named("clean") {
    dependsOn(":ant-clean")
}

tasks.named("jingtrang") {
    dependsOn(":jars")
}

tasks.named("build") {
	dependsOn(jingTrang)
}

val antJar: TaskProvider<Task> = tasks.named("ant-jar")

// https://stackoverflow.com/questions/27993814/only-run-task-if-another-isnt-up-to-date-in-gradle
project.gradle.taskGraph.whenReady {
    // make the antJar task have the same inputs/outputs
    antJar.get().inputs.files(jars.inputs.files)
    antJar.get().outputs.files(jars.outputs.files)
}

defaultTasks(":build")
