import org.gradle.internal.logging.LoggingOutputInternal
import org.gradle.internal.logging.events.OutputEvent
import org.gradle.internal.logging.events.OutputEventListener

tasks.withType(Javadoc) {
    def exceptions = []
    doFirst {
        gradle.services.get(LoggingOutputInternal).addOutputEventListener(new OutputEventListener() {
            void onOutput(OutputEvent event) {
                if (event.toString() =~ " warning: ") {
                    exceptions << new GradleException("Javadoc warning: ${event.toString()}")
                }
            }
        })
    }
    doLast {
        exceptions.each {
            throw it
        }
    }
}

task pathingJar(type: Jar, description: "Produces a 'pathing' JAR whose manifest class-path contains project runtime dependencies") {
    dependsOn configurations.runtimeClasspath
    archiveAppendix = "pathing"

    doFirst {
        manifest {
            attributes "Class-Path":
            configurations.runtimeClasspath.files.collect {
                it.toURL().toString().replaceFirst("/file:/+/", "/")
            }
            .join(" ")
        }
    }
}

tasks.register('testJar', Jar) {
    dependsOn testClasses
    description = "Archive the testClasses"
    archiveClassifier.set("tests")
    from sourceSets.test.output
}

tasks.register('sourcesJar', Jar) {
    dependsOn classes
    archiveClassifier.set("sources")
    from sourceSets.main.allSource
}

tasks.register('resourcesJar', Jar) {
    archiveClassifier.set("resources")
    from project.file("src/main/resources")
}

tasks.register('javadocJar', Jar) {
    dependsOn javadoc
    archiveClassifier.set("javadoc")
    from javadoc.destinationDir
}

task showConfiguration {
    description "Shows the configuration used by the build"
    doLast() {
        def cfg = project.hasProperty("configuration") ? project.property("configuration") : "compile"
        configurations.getByName(cfg).each { println it }
    }
}

task downloadDependencies {
    description "Pre-download project dependencies for all configurations"
    doLast {
        configurations.getAsMap().each { name, config ->
            logger.info "Retrieving dependencies for $project:$name"
            try {
                config.files
            } catch (e) {
                project.logger.info e.message
            }
        }
    }
}

task outputDependenciesWithoutLicense(description: "Output dependencies without approved license") {
    doLast {
        def results = file("${project.buildDir}/licenses/dependencies-without-allowed-license.json")
        if (results.exists()) {
            def slurper = new groovy.json.JsonSlurper()
            def dependencies = slurper.parseText(results.text)
            if (!dependencies.dependenciesWithoutAllowedLicenses.isEmpty()) {
                println results.text
                throw new GradleException("Dependencies found without allowed licenses")
            }
        }
    }
}

