import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction

class ProvideBuildClasspathTask extends DefaultTask {
    @OutputFile File outFile

    @TaskAction
    public void writeProperties() throws Exception {
        final List<String> paths = new ArrayList<>()

        project.rootProject.allprojects.each { Project otherProject ->
            def match = otherProject.name =~ /shadows\/(.*)/
            if (match.matches()) {
                def artifactName = "${otherProject.group}:${otherProject.mavenArtifactName}:${otherProject.version}"
                File classesDir = otherProject.sourceSets['main'].output.classesDir
                File resourcesDir = otherProject.sourceSets['main'].output.resourcesDir
                paths << "${artifactName.replaceAll(/:/, '\\\\:')}: ${classesDir}:${resourcesDir}"
            }
        }

        AndroidSdk.ALL_SDKS.each { androidSdk ->
            def config = project.configurations.create("sdk${androidSdk.apiLevel}")
            project.dependencies.add("sdk${androidSdk.apiLevel}", androidSdk.coordinates)
            paths << "${androidSdk.coordinates.replaceAll(/:/, '\\\\:')}: ${config.files.join(':')}"
        }

        File outDir = outFile.parentFile
        if (!outDir.directory) outDir.mkdirs()
        outFile.withPrintWriter { out ->
            out.println("# GENERATED by ${this} -- do not edit")
            paths.each { path -> out.println path }
        }
    }
}