//ant.importBuild 'build.xml'
import groovy.xml.MarkupBuilder
import java.util.zip.ZipFile

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

configurations {
    corelibs
    optlibs
    testdatalibs
    examplelibs
}

dependencies {
    corelibs project(':jme3-blender')
    corelibs project(':jme3-core')
    corelibs project(':jme3-desktop')
    corelibs project(':jme3-effects')
    corelibs project(':jme3-jbullet')
    corelibs project(':jme3-jogg')
    corelibs project(':jme3-lwjgl')
    corelibs project(':jme3-networking')
    corelibs project(':jme3-niftygui')
    corelibs project(':jme3-plugins')
    corelibs project(':jme3-terrain')
    
    optlibs project(':jme3-bullet')
    optlibs project(':jme3-jogl')
    optlibs project(':jme3-android')
    optlibs project(':jme3-ios')
    optlibs project(':jme3-android-native')
    optlibs project(':jme3-bullet-native')
    testdatalibs project(':jme3-testdata')

    examplelibs project(':jme3-examples')
    
}

artifacts {
    //    jar null
}

task checkPlatformConfig {
    description = "Downloads the NetBeans platform base and registers it in the SDK project if needed"
    def platformFile = file("nbproject/private/platform-private.properties")
    if(!platformFile.exists()){
        def netbeansFolder = file("../netbeans")
        if(!netbeansFolder.exists()){
            println "Downloading NetBeans Platform base, this only has to be done once.."
            def f = file("netbeans.zip")
            new URL(netbeansUrl).withInputStream{ i -> f.withOutputStream{ it << i }}
            copy{
                from zipTree(f)
                into "../"
            }
            f.delete()
        }
        file("nbproject/private/").mkdirs()
        platformFile.createNewFile()
        platformFile.write("nbplatform.default.netbeans.dest.dir=${netbeansFolder.absolutePath.replace('\\','/')}\r\n"+\
                           "nbplatform.default.harness.dir=${netbeansFolder.absolutePath.replace('\\','/')}/harness\r\n")
    }
}

task copyBaseLibs(dependsOn:configurations.corelibs) <<{
    description "Copies the library files needed to run the SDK to "+
                "jme3-core-baselibs and jme3-core-libraries"

    // for each dependency in corelibs..
    project.configurations.corelibs.dependencies.each {dep ->
        // copy built jme3 jar files to jme3-core-baselibs
        dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact->
            if(artifact.classifier == "sources"){
            } else if(artifact.classifier == "javadoc"){
            } else{
                copy {
                    from artifact.file
                    into "jme3-core-baselibs/release/modules/ext/"
                }
            }
        }
        // copy external jar files to jme3-core-libraries
        copy {
            from dep.dependencyProject.configurations.compile.copyRecursive({ !(it instanceof ProjectDependency); }).resolve()
            into "jme3-core-libraries/release/modules/ext/"
        }
    }
}
copyBaseLibs.inputs.files configurations.corelibs.resolve()
copyBaseLibs.outputs.dir "jme3-core-baselibs/release/modules/ext/"
copyBaseLibs.outputs.dir "jme3-core-libraries/release/modules/ext/"

task createBaseXml(dependsOn: configurations.corelibs) <<{
    description "Creates the project.xml files for "+
                "jme3-core-baselibs and jme3-core-libraries"
    def jmeJarFiles = [] // jme3 jar files
    def externalJarFiles = [] // external jar files
    
    // collect jar files
    project.configurations.corelibs.dependencies.each {dep ->
        // collect external jar files
        dep.dependencyProject.configurations.compile.copyRecursive({ !(it instanceof ProjectDependency); }).resolve().each{ file->
            externalJarFiles.add(file)
        }
        // collect internal jar files (classes, sources and javadoc)
        dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact->
            if(artifact.classifier == "sources"){
            } else if(artifact.classifier == "javadoc"){
            } else{
                if(!jmeJarFiles.contains(artifact.file)){
                    jmeJarFiles.add(artifact.file)
                }
            }
        }
    }

    // collect base packages
    def packages = []
    jmeJarFiles.each{jarFile ->
        ZipFile file = new ZipFile(jarFile)
        file.entries().each { entry ->  
            if(entry.name.endsWith('.class')){
                // TODO: "/" works on windows?
                def pathPart = entry.name.substring(0,entry.name.lastIndexOf('/'))
                def classPath = pathPart.replace('/','.');
                if(!packages.contains(classPath)){
                    packages.add(classPath)
                }
            }
        } 
    }
    
    // collect library packages
    def extPackages = []
    externalJarFiles.each{jarFile ->
        ZipFile file = new ZipFile(jarFile)
        file.entries().each { entry ->  
            if(entry.name.endsWith('.class')){
                // TODO: "/" works on windows?
                def pathPart = entry.name.substring(0,entry.name.lastIndexOf('/'))
                def classPath = pathPart.replace('/','.');
                if(!extPackages.contains(classPath)){
                    extPackages.add(classPath)
                }
            }
        } 
    }
    
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    xml.mkp.xmlDeclaration(version:'1.0')
    xml.project(xmlns:"http://www.netbeans.org/ns/project/1"){
        type "org.netbeans.modules.apisupport.project"
        configuration {
            data(xmlns:"http://www.netbeans.org/ns/nb-module-project/3") {
                "code-name-base" "com.jme3.gde.core.baselibs"
                "suite-component"{}
                "module-dependencies"{
                    dependency{
                        "code-name-base" "com.jme3.gde.core.libraries"
                        "build-prerequisite"{}
                        "compile-dependency"{}
                        "run-dependency"{
                            "release-version" "1"
                            "specification-version" "3.0.0"
                        }
                    }
                }
                "public-packages"{
                    packages.each{
                        "package" it
                    }
                }
                jmeJarFiles.each{jarFile ->
                    "class-path-extension"{
                        "runtime-relative-path" "ext/${jarFile.name}"
                        "binary-origin" "release/modules/ext/${jarFile.name}"
                    }
                }
            }
        }
    }
    // write XML file
    File baselibsProjectFile = file("jme3-core-baselibs/nbproject/project.xml");
    baselibsProjectFile.write(writer.toString())

    def extWriter = new StringWriter()
    def extXml = new MarkupBuilder(extWriter)
//    extXml.mkp.xmlDeclaration(version:'1.0')
    extXml.project(xmlns:"http://www.netbeans.org/ns/project/1"){
        type "org.netbeans.modules.apisupport.project"
        configuration {
            data(xmlns:"http://www.netbeans.org/ns/nb-module-project/3") {
                "code-name-base" "com.jme3.gde.core.libraries"
                "suite-component"{}
                "module-dependencies"{}
                "public-packages"{
                    extPackages.each{
                        "package" it
                    }
                }
                externalJarFiles.each{jarFile ->
                    "class-path-extension"{
                        "runtime-relative-path" "ext/${jarFile.name}"
                        "binary-origin" "release/modules/ext/${jarFile.name}"
                    }
                }
            }
        }
    }
    // write XML file
    File librariesProjectFile = file("jme3-core-libraries/nbproject/project.xml");
    librariesProjectFile.write(extWriter.toString())
}
createBaseXml.inputs.files configurations.corelibs.resolve()
createBaseXml.outputs.file "jme3-core-baselibs/nbproject/project.xml"
createBaseXml.outputs.file "jme3-core-libraries/nbproject/project.xml"

task copyProjectLibs(dependsOn: [configurations.corelibs, configurations.testdatalibs]) <<{
    description "Copies the jar files needed to supply the J2SE Libraries in the "+
                "SDK to jme3-project-baselibs and jme3-project-libraries"

    // for each dependency in corelibs and optlibs..
    def deps = []
    deps.addAll(project.configurations.corelibs.dependencies)
    deps.addAll(project.configurations.optlibs.dependencies)
    deps.each {dep ->
        // copy jme3 jar files, sources and javadocs to jme3-project-baselibs
        dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact->
            if(artifact.classifier == "sources"){
                copy {
                    from artifact.file
                    into "jme3-project-baselibs/release/libs/"
                }
            } else if(artifact.classifier == "javadoc"){
                copy {
                    from artifact.file
                    into "jme3-project-baselibs/release/libs/"
                }
            } else{
                copy {
                    from artifact.file
                    into "jme3-project-baselibs/release/libs/"
                }
            }
        }
        // copy external jar files to jme3-project-libraries
        copy {
            from dep.dependencyProject.configurations.compile.copyRecursive({ !(it instanceof ProjectDependency); }).resolve()
            into "jme3-project-libraries/release/libs/"
        }
    }
    
    project.configurations.testdatalibs.dependencies.each {dep ->
        // copy jme3 test data to jme3-project-testdata
        dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact->
            if(artifact.classifier == "sources"){
            } else if(artifact.classifier == "javadoc"){
            } else{
                copy {
                    from artifact.file
                    into "jme3-project-testdata/release/libs/"
                    rename ("jme3-testdata(.*)", "jme3-testdata.jar")
                }
            }
        }
    }
}
copyProjectLibs.inputs.files configurations.corelibs.resolve()
copyProjectLibs.inputs.files configurations.optlibs.resolve()
copyProjectLibs.inputs.files configurations.testdatalibs.resolve()
copyProjectLibs.outputs.dir "jme3-project-baselibs/release/libs/"
copyProjectLibs.outputs.dir "jme3-project-libraries/release/libs/"
copyProjectLibs.outputs.dir "jme3-project-testdata/release/libs/"

// workaround method to add a tag with the name "name" and "file" to an XML MarkupBuilder
def makeName(builder, nameR) { builder.name nameR }
def makeFile(builder, nameR) { builder.file(name:nameR, url:nameR) }

task createProjectXml(dependsOn: configurations.corelibs) <<{
    description "Creates needed J2SE library and layer XML files in jme3-project-baselibs"
    
    def eol = System.properties.'line.separator' 
    def j2seLibraries = [] // created J2SE library descriptors
    
    // for each dependency in corelibs..
    def deps = []
    deps.addAll(project.configurations.corelibs.dependencies)
    deps.addAll(project.configurations.optlibs.dependencies)
    deps.each {dep ->
        def jmeJarFiles = [] // jme3 jar files
        def jmeSourceFiles = [] // jme3 sources
        def jmeJavadocFiles = [] // jme3 javadoc
        def externalJarFiles = [] // external jar files
        j2seLibraries.add(dep.dependencyProject.name+".xml")
        // collect external jar files
        dep.dependencyProject.configurations.compile.copyRecursive({ !(it instanceof ProjectDependency); }).resolve().each{ file->
            externalJarFiles.add(file.name)
        }
        // collect internal jar files (classes, sources and javadoc)
        dep.dependencyProject.configurations.archives.allArtifacts.each{ artifact->
            if(artifact.classifier == "sources"){
                jmeSourceFiles.add(artifact.file.name)
            } else if(artifact.classifier == "javadoc"){
                jmeJavadocFiles.add(artifact.file.name)
            } else{
                if(!jmeJarFiles.contains(artifact.file.name)){
                    jmeJarFiles.add(artifact.file.name)
                }
            }
        }
        // create J2SE library descriptor xml file
        def libraryWriter = new StringWriter()
        def libraryXml = new MarkupBuilder(libraryWriter)
//        xml.mkp.xmlDeclaration(version:'1.0')
        libraryWriter << '<?xml version="1.0" encoding="UTF-8"?>' << eol 
        libraryWriter << '<!DOCTYPE library PUBLIC "-//NetBeans//DTD Library Declaration 1.0//EN" "http://www.netbeans.org/dtds/library-declaration-1_0.dtd">' << eol
        libraryXml.library(version:"1.0", encoding: "UTF-8"){
            makeName(libraryXml, "${dep.dependencyProject.name}")
            type "j2se"
            "localizing-bundle" "com.jme3.gde.project.baselibs.Bundle"
            volume{
                type "classpath"
                jmeJarFiles.each{jar ->
                    resource "jar:nbinst://com.jme3.gde.project.baselibs/libs/${jar}!/"
                }
                externalJarFiles.each{jar ->
                    resource "jar:nbinst://com.jme3.gde.project.libraries/libs/${jar}!/"
                }
            }
            volume{
                type "src"
                jmeSourceFiles.each{jar ->
                    resource "jar:nbinst://com.jme3.gde.project.baselibs/libs/${jar}!/"
                }
            }
            volume{
                type "javadoc"
                jmeJavadocFiles.each{jar ->
                    resource "jar:nbinst://com.jme3.gde.project.baselibs/libs/${jar}!/"
                }
            }
        }
        // write XML file
        File libraryXmlFile = file("jme3-project-baselibs/src/com/jme3/gde/project/baselibs/${dep.dependencyProject.name}.xml");
        libraryXmlFile.write(libraryWriter.toString())
    }

    // create layer.xml file with entries of library xml files
    def layerWriter = new StringWriter()
    def layerXml = new MarkupBuilder(layerWriter)
//    layerXml.mkp.xmlDeclaration(version:'1.0')
    layerWriter << '<?xml version="1.0" encoding="UTF-8"?>' << eol 
    layerWriter << '<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">' << eol
    layerXml.filesystem{
        folder(name:"org-netbeans-api-project-libraries"){
            folder(name:"Libraries"){
                j2seLibraries.each{lib ->
                    makeFile(layerXml, lib)
                }
            }
        }
    }
    File layerXmlFile = file("jme3-project-baselibs/src/com/jme3/gde/project/baselibs/layer.xml");
    layerXmlFile.write(layerWriter.toString())
}
createProjectXml.inputs.files configurations.corelibs.resolve()
createProjectXml.inputs.files configurations.optlibs.resolve()
createProjectXml.outputs.dir "jme3-project-baselibs/src/com/jme3/gde/project/baselibs/"

task copyTestSources <<{
    project.configurations.examplelibs.dependencies.each{dep ->
        copy{
            from dep.dependencyProject.sourceSets*.allSource
            into "JME3TestsTemplate/src/"
        }
        copy{
            from dep.dependencyProject.sourceSets*.allSource
            into "JME3TestsTemplateAndroid/src/"
        }
    }
}
copyTestSources.inputs.files project.configurations.examplelibs
copyTestSources.outputs.dir "JME3TestsTemplate/src/"
copyTestSources.outputs.dir "JME3TestsTemplateAndroid/src/"

ant.properties['plugins.version'] = jmeVersion
ant.properties['app.version']= jmeMainVersion + "-" + jmeVersionTag

task buildSdk(dependsOn: [copyBaseLibs, copyProjectLibs, createProjectXml, createBaseXml, copyTestSources]) <<{
    ant.propertyfile(file: "nbproject/project.properties") {
        entry( key: "plugins.version", value: "${jmeVersion}")
        entry( key: "app.version", value: "${jmeMainVersion + "-" + jmeVersionTag}")
    }
    ant.ant(dir: ".", antfile: "build.xml", target: "build")
}
buildSdk.inputs.files configurations.corelibs.resolve()
buildSdk.inputs.files configurations.optlibs.resolve()
file('.').eachDir{
    if(it.name.startsWith("jme3-") && it.isDirectory()){
        buildSdk.inputs.dir it
    }
}
buildSdk.outputs.dir "build"

task cleanSdk() <<{
    ant.ant(dir: ".", antfile: "build.xml", target: "clean")
    file("jme3-core-baselibs/release/").deleteDir()
    file("jme3-core-libraries/release/").deleteDir()
    file("jme3-project-baselibs/release/").deleteDir()
    file("jme3-project-libraries/release/").deleteDir()
    file("JME3TestsTemplate/src/jmetest/").deleteDir()
    file("JME3TestsTemplateAndroid/src/jmetest/").deleteDir()
}

jar.dependsOn(buildSdk)
clean.dependsOn(cleanSdk);


