apply plugin: 'cpp'

String bulletUrl = 'http://bullet.googlecode.com/files/bullet-2.82-r2704.zip'
String bulletFolder = 'bullet-2.82-r2704'
String bulletSrcPath = bulletFolder + '/src'
String bulletZipFile = 'bullet.zip'

//Directories for the android ndk build.
String ndkWorkingPath = 'src/native'
String jmeAndroidPath = ndkWorkingPath + '/android'
String jmeCppPath = ndkWorkingPath + '/cpp'
String jniPath = ndkWorkingPath + '/jni'
String ndkOutputPath = ndkWorkingPath + '/libs'

if (!hasProperty('mainClass')) {
    ext.mainClass = ''
}

dependencies {
    compile project(':jme3-bullet')
}

// C++ sources for binary compilation
sources {
    bulletjme {
        cpp {
            source {
                srcDir 'src/native/cpp'
                srcDir bulletSrcPath
                exclude 'BulletMultiThreaded/GpuSoftBodySolvers/**'
                include '**/*.cpp'
            }
            exportedHeaders {
                srcDir 'src/native/cpp'
                srcDir bulletSrcPath
                include '**/*.h'
            }
        }
    }
}

// Java source sets for IDE acces and source jar bundling / mavenization
sourceSets {
    main {
        java {
            srcDir 'src/native/cpp'
            srcDir 'src/native/android'
        }
    }
}

// Set of target platforms, will be available based on build system
targetPlatforms {
//    osx_universal { // TODO: universal binary doesn't work?
//        architecture 'x86_64'
//        architecture 'x86'
//        operatingSystem 'osx'
//    }
    osx_x86 {
        architecture "x86"
        operatingSystem "osx"
    }
    osx_x64 {
        architecture "x86_64"
        operatingSystem "osx"
    }
    linux_x86 {
        architecture "x86"
        operatingSystem "linux"
    }
    linux_x86_64 {
        architecture "x86_64"
        operatingSystem "linux"
    }
    windows_x86 {
        architecture "x86"
        operatingSystem "windows"
    }
    windows_x86_64 {
        architecture "x86_64"
        operatingSystem "windows"
    }
}

// Defines created C++ libraries
libraries {
    bulletjme {
    }
    all {
        binaries.all {
            cppCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include"
            if (targetPlatform.operatingSystem.name == "osx") {
                cppCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include/darwin"
            } else if (targetPlatform.operatingSystem.name == "linux") {
                cppCompiler.args '-I', "${org.gradle.internal.jvm.Jvm.current().javaHome}/include/linux"
                cppCompiler.args "-fPIC"
                cppCompiler.args "-fpermissive"
                cppCompiler.args "-static-libgcc"
                linker.args "-static"
            } else if (targetPlatform.operatingSystem.name == "windows") {
                cppCompiler.args "-I${org.gradle.internal.jvm.Jvm.current().javaHome}/include/win32"
//                cppCompiler.define('WIN32')
//                linker.args 'Shlwapi.lib', 'Advapi32.lib'
            }
        }
    }
}

// Download bullet if not available
task downloadBullet(type: MyDownload) {
    sourceUrl = bulletUrl
    target = file(bulletZipFile)
}

// Unzip bullet if not available
task unzipBullet(type: Copy) {
    def zipFile = file(bulletZipFile)
    def outputDir = file(".")

    from zipTree(zipFile)
    into outputDir
}
unzipBullet.dependsOn {
    def zipFilePath = project.projectDir.absolutePath + File.separator + bulletZipFile
    def zipFile = new File(zipFilePath)
//    println "zipFile path: " + zipFile.absolutePath
//    println "zipFile exists: " + zipFile.exists()
    if (!zipFile.exists()) {
        downloadBullet
    }
}

compileJava.dependsOn {
    def bulletUnzipDir = new File(project.projectDir.absolutePath + File.separator + bulletFolder)
//    println "bulletUnzipDir path: " + bulletUnzipDir.absolutePath
//    println "bulletUnzipDir exists: " + bulletUnzipDir.isDirectory()
    if (!bulletUnzipDir.isDirectory()) {
        unzipBullet
    }
}

//task buildAllExecutables {
//    dependsOn binaries.withType(SharedLibraryBinary).matching {
//        it.buildable
//    }
//}

// Adds all built binaries to java jar task
binaries.withType(SharedLibraryBinary) { binary ->
    if (!buildable) {
        //TODO: obtain elsewhere if not available
        return
    }
    // Get builder of this binary
    def builderTask = binary.tasks.builder
    // Add output to jar file
    jar.into("native/${targetPlatform.operatingSystem.name}/${targetPlatform.architecture.name}") { from builderTask.outputFile }
    // Add depend on build
    jar.dependsOn builderTask
}

// Helper class to wrap ant dowload task
class MyDownload extends DefaultTask {
    @Input
    String sourceUrl

    @OutputFile
    File target

    @TaskAction
    void download() {
       ant.get(src: sourceUrl, dest: target)
    }
}


// ANDROID NDK BUILD

// Copy Bullet files to jni directory
task copyBullet(type: Copy) {
    def sourceDir = file(bulletSrcPath)
    def outputDir = file(jniPath)

    from sourceDir
    into outputDir
}
copyBullet.dependsOn {
    def bulletUnzipDir = new File(project.projectDir.absolutePath + File.separator + bulletFolder)
    if (!bulletUnzipDir.isDirectory()) {
        unzipBullet
    }
}

// Copy jME cpp native files to jni directory
task copyJmeCpp(type: Copy, dependsOn:copyBullet) {
    def sourceDir = file(jmeCppPath)
    def outputDir = file(jniPath)

    from sourceDir
    into outputDir
}

// Copy jME android native files to jni directory
task copyJmeAndroid(type: Copy, dependsOn:copyJmeCpp) {
    def sourceDir = file(jmeAndroidPath)
    def outputDir = file(jniPath)

    from sourceDir
    into outputDir
}

task buildNative(type: Exec, dependsOn:copyJmeAndroid) {
    String ndkBuildFile = "ndk-build"
    // if windows, use ndk-build.cmd instead
    if (System.properties['os.name'].toLowerCase().contains('windows')) {
        ndkBuildFile = "ndk-build.cmd"
    }

    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
    }

    // need to target android-9 so the ndk can pull in the opensl library
    args 'TARGET_PLATFORM=android-9'
    workingDir ndkWorkingPath
    executable ndkBuildPath
}

task jarAndroidLibs(type: Jar, dependsOn:buildNative) {
    String jarName = project.name + '-android'
    from ndkOutputPath
    into('lib')
    baseName = jarName
}
//println jar.archiveName
//println relativePath(jar.destinationDir)
//println relativePath(jar.archivePath)
//println jarAndroidLibs.archiveName
//println relativePath(jarAndroidLibs.destinationDir)
//println relativePath(jarAndroidLibs.archivePath)

jar.dependsOn {
    def ndkDir = new File(ndkPath)
    if (ndkDir.isDirectory()) {
        buildNative
    }
}
jar.dependsOn jarAndroidLibs

//adds files into existing jar file
//jar.into("lib") { from ndkOutputPath }


artifacts {
    archives jarAndroidLibs
}
