import org.gradle.api.artifacts.*

apply plugin: 'base' // To add "clean" task to the root project.
//apply plugin: 'java-library-distribution'

// This is applied to all sub projects
subprojects {
    // Don't add to native builds
    //    if(!project.name.endsWith('native')){
    apply from: rootProject.file('common.gradle')
    //    }
}

task run(dependsOn: ':jme3-examples:build', type: JavaExec) {
    description = 'Run the jME3 examples'
    main = 'jme3test.TestChooser'
    classpath += files(subprojects.collect{project ->
            project.sourceSets*.runtimeClasspath})
//    classpath += files(subprojects.collect {project ->
//            project.sourceSets*.output})
//    classpath = sourceSets.main.runtimeClasspath
//    args 'mrhaki'
//    systemProperty 'simple.message', 'Hello '
}

defaultTasks 'run'

task libDist(dependsOn: subprojects.build) << {
//    description 'Builds and copies the engine binaries, sources and javadoc to build/libDist'
    File libFolder = mkdir("$buildDir/libDist/lib")
    File sourceFolder = mkdir("$buildDir/libDist/sources")
    File javadocFolder = mkdir("$buildDir/libDist/javadoc")
    subprojects.each {project ->
        if(project.ext.mainClass == ''){
            project.tasks.withType(Jar).each {archiveTask ->
                if(archiveTask.classifier == "sources"){
                    copy {
                        from archiveTask.archivePath
                        into sourceFolder
                        rename {project.name + '-' + archiveTask.classifier +'.'+ archiveTask.extension}
                    }
                } else if(archiveTask.classifier == "javadoc"){
                    copy {
                        from archiveTask.archivePath
                        into javadocFolder
                        rename {project.name + '-' + archiveTask.classifier +'.'+ archiveTask.extension}
                    }
                } else{
                    copy {
                        from archiveTask.archivePath
                        into libFolder
                        rename {project.name + '.' + archiveTask.extension}
                    }
                }
            }
        }
    }
}

task createZipDistribution(type:Zip,dependsOn:["dist","libDist"], description:"Package the nightly zip distribution"){    
        archiveName "jME"+jmeVersion+"_"+jmeVersionTag+"_"+new Date().format("yyyy-MM-dd")+".zip"
       
        into("/") {
             from {"./dist"}
        }            
        into("/sources") {
            from {"$buildDir/libDist/sources"}     
        }   
        println archiveName       
}

task copyLibs(type: Copy){
//    description 'Copies the engine dependencies to build/libDist'
    from {
        subprojects*.configurations*.compile*.copyRecursive({ !(it instanceof ProjectDependency); })*.resolve()
    }

    into "$buildDir/libDist/lib-ext" //buildDir.path + '/' + libsDirName + '/lib'
}

task dist(dependsOn: [':jme3-examples:dist', 'mergedJavadoc']){
    description 'Creates a jME3 examples distribution with all jme3 binaries, sources, javadoc and external libraries under ./dist'
}

task mergedJavadoc(type: Javadoc, description: 'Creates Javadoc from all the projects.') {
    title = 'jMonkeyEngine3'
    destinationDir = mkdir("dist/javadoc")

    // Allows Javadoc to be generated on Java 8 despite doclint errors.
    if (JavaVersion.current().isJava8Compatible()) {
        options.addStringOption('Xdoclint:none', '-quiet')
    }
    
    // Note: The closures below are executed lazily.
    source subprojects.collect {project ->
        project.sourceSets*.allJava
    }
//    classpath = files(subprojects.collect {project ->
//            project.sourceSets*.compileClasspath})
    //    source {
    //        subprojects*.sourceSets*.main*.allSource
    //    }
    classpath.from {
        subprojects*.configurations*.compile*.copyRecursive({ !(it instanceof ProjectDependency); })*.resolve()
    }
}

task mergedSource(type: Copy){

}

task wrapper(type: Wrapper, description: 'Creates and deploys the Gradle wrapper to the current directory.') {
    gradleVersion = '1.12'
}

String findNDK() {
    def ndkBuildFile = "ndk-build"
    // if windows, use ndk-build.cmd instead
    if (System.properties['os.name'].toLowerCase().contains('windows')) {
        ndkBuildFile = "ndk-build.cmd"
    }

    // ndkPath is defined in the root project gradle.properties file
    String ndkBuildPath = ndkPath + File.separator + ndkBuildFile
    //Use the environment variable for the NDK location if defined
    if (System.env.ANDROID_NDK != null) {
        ndkBuildPath = System.env.ANDROID_NDK + File.separator + ndkBuildFile
    }
    if (new File(ndkBuildPath).exists()) {
        return ndkBuildPath
    } else {
        return null
    }
}

boolean checkNdkExists(String ndkCommandPath) {
//    String ndkCommandPath = findNDK()
    if (ndkCommandPath != null && new File(ndkCommandPath).exists()) {
        return true
    } else {
        return false
    }
}

ext {
    ndkCommandPath = findNDK()
    ndkExists = checkNdkExists(ndkCommandPath)
}

//class IncrementalReverseTask extends DefaultTask {
//    @InputDirectory
//    def File inputDir
//
//    @OutputDirectory
//    def File outputDir
//
//    @Input
//    def inputProperty
//
//    @TaskAction
//    void execute(IncrementalTaskInputs inputs) {
//        println inputs.incremental ? "CHANGED inputs considered out of date" : "ALL inputs considered out of date"
//        inputs.outOfDate { change ->
//            println "out of date: ${change.file.name}"
//            def targetFile = new File(outputDir, change.file.name)
//            targetFile.text = change.file.text.reverse()
//        }
//
//        inputs.removed { change ->
//            println "removed: ${change.file.name}"
//            def targetFile = new File(outputDir, change.file.name)
//            targetFile.delete()
//        }
//    }
//}