buildscript{
    repositories{
        mavenLocal()
        mavenCentral()
        google()
        maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }

    dependencies{
        classpath 'com.mobidevelop.robovm:robovm-gradle-plugin:2.3.7'
        classpath "com.badlogicgames.gdx:gdx-tools:1.9.10"
        classpath "com.badlogicgames.packr:packr:2.1-SNAPSHOT"
    }
}

allprojects{
    version = 'release'

    ext{
        versionNumber = '4'
        versionModifier = 'release'
        if(!project.hasProperty("versionType")) versionType = 'official'
        appName = 'Mindustry'
        gdxVersion = '1.9.10'
        roboVMVersion = '2.3.7'
        arcHash = null

        debugged = {
            return new File(projectDir.parent, '../debug').exists() && !project.hasProperty("release") && project.hasProperty("args")
        }

        localArc = {
            return (!project.hasProperty("release")) && new File(projectDir.parent, '../Arc').exists()
        }

        getArcHash = {
            //get latest commit hash from github since JITPack's '-snapshot' version doesn't work correctly
            if(arcHash == null){
                try{
                    arcHash = 'git ls-remote https://github.com/Anuken/Arc.git'.execute().text.split("\t")[0]
                }catch(e){
                    e.printStackTrace()
                    arcHash = "-SNAPSHOT"
                }
            }
            return arcHash
        }

        arcModule = { String name ->
            if(localArc()){
                return project(":Arc:$name")
            }else{
                //skip to last submodule
                if(name.contains(':')) name = name.split(':').last()
                return "com.github.Anuken.Arc:$name:${getArcHash()}"
            }
        }

        generateDeployName = { String platform ->
            if(platform == "windows"){
                platform += "64"
            }
            platform = platform.capitalize()

            if(platform.endsWith("64") || platform.endsWith("32")){
                platform = "${platform.substring(0, platform.length() - 2)}-${platform.substring(platform.length() - 2)}bit"
            }

            return "[${platform}]${getModifierString()}[${getNeatVersionString()}]${appName}"
        }

        getVersionString = {
            String buildVersion = getBuildVersion()
            return "$versionNumber-$versionModifier-$buildVersion"
        }

        getNeatVersionString = {
            String buildVersion = getBuildVersion()
            return "v$buildVersion"
        }

        getModifierString = {
            if(versionModifier != "release"){
                return "[${versionModifier.toUpperCase()}]"
            }
            return ""
        }

        getBuildVersion = {
            if(!project.hasProperty("buildversion")) return "custom build"
            return project.getProperties()["buildversion"]
        }

        getPackage = {
            return project.ext.mainClassName.substring(0, project.ext.mainClassName.indexOf("desktop") - 1)
        }

        generateLocales = {
            def output = 'en\n'
            def bundles = new File(project(':core').projectDir, 'assets/bundles/')
            bundles.listFiles().each{ other ->
                if(other.name == "bundle.properties") return
                output += other.name.substring("bundle".length() + 1, other.name.lastIndexOf('.')) + "\n"
            }
            new File(project(':core').projectDir, 'assets/locales').text = output
        }

        writeVersion = {
            def pfile = new File(project(':core').projectDir, 'assets/version.properties')
            def props = new Properties()

            try{
                pfile.createNewFile()
            }catch(Exception ignored){
            }

            if(pfile.exists()){
                props.load(new FileInputStream(pfile))

                String buildid = getBuildVersion()

                props["type"] = versionType
                props["number"] = versionNumber
                props["modifier"] = versionModifier
                props["build"] = buildid

                props.store(pfile.newWriter(), "Autogenerated file. Do not modify.")
            }
        }
    }

    repositories{
        mavenLocal()
        mavenCentral()
        maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven{ url "https://oss.sonatype.org/content/repositories/releases/" }
        maven{ url 'https://jitpack.io' }
        jcenter()
    }

    tasks.withType(Javadoc).all{ enabled = false }
}

project(":desktop"){
    apply plugin: "java"

    dependencies{
        compile project(":core")
        compile project(":net")

        if(debugged()) compile project(":debug")

        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"

        compile arcModule("backends:backend-sdl")
        compile 'com.github.MinnDevelopment:java-discord-rpc:v2.0.2'
    }
}

project(":ios"){
    apply plugin: "java"
    apply plugin: "robovm"

    task incrementConfig{
        def vfile = file('robovm.properties')

        def props = new Properties()
        if(vfile.exists()){
            props.load(new FileInputStream(vfile))
        }

        props['app.id'] = 'io.anuke.mindustry'
        props['app.version'] = '4.0'
        props['app.mainclass'] = 'io.anuke.mindustry.IOSLauncher'
        props['app.executable'] = 'IOSLauncher'
        props['app.name'] = 'Mindustry'
        props['app.build'] = (!props.containsKey("app.build") ? 40 : props['app.build'].toInteger() + 1) + ""
        props.store(vfile.newWriter(), null)
    }

    dependencies{
        compile project(":core")
        compile project(":net")
        compileOnly project(":annotations")

        compile arcModule("backends:backend-robovm")

        compile "com.mobidevelop.robovm:robovm-rt:$roboVMVersion"
        compile "com.mobidevelop.robovm:robovm-cocoatouch:$roboVMVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-ios"
    }
}

project(":core"){
    apply plugin: "java"

    task preGen{
        generateLocales()
    }

    dependencies{
        if(System.properties["user.name"] == "anuke"){
            task cleanGen{
                doFirst{
                    delete{
                        delete "../core/src/io/anuke/mindustry/gen/"
                    }
                }
            }

            task copyGen{
                doLast{
                    copy{
                        from("../core/build/generated/sources/annotationProcessor/java/main/io/anuke/mindustry/gen"){
                            include "**/*.java"
                        }

                        into "../core/src/io/anuke/mindustry/gen"
                    }
                }
            }

            compileJava.dependsOn(cleanGen)
            compileJava.finalizedBy(copyGen)
        }

        compileJava.dependsOn(preGen)

        compile arcModule("arc-core")
        compile arcModule("extensions:freetype")
        compile arcModule("extensions:arcnet")
        if(localArc() && debugged()) compile arcModule("extensions:recorder")

        compileOnly project(":annotations")
        annotationProcessor project(":annotations")
    }
}

project(":server"){
    apply plugin: "java"

    dependencies{
        compile project(":core")
        compile project(":net")
        compile arcModule("backends:backend-headless")
    }
}

project(":tests"){
    apply plugin: "java"

    dependencies{
        testImplementation project(":core")
        testImplementation "org.junit.jupiter:junit-jupiter-params:5.3.1"
        testImplementation "org.junit.jupiter:junit-jupiter-api:5.3.1"
        testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.3.1"
        compile arcModule("backends:backend-headless")
    }

    test{
        useJUnitPlatform()
        workingDir = new File("../core/assets")
    }
}

project(":tools"){
    apply plugin: "java"

    dependencies{
        compile project(":core")

        //for render tests
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"

        compile arcModule("backends:backend-sdl")
    }
}

project(":annotations"){
    apply plugin: "java"

    dependencies{
        compile 'com.squareup:javapoet:1.11.0'
        compile files("${System.getProperty('java.home')}/../lib/tools.jar")
    }
}

project(":net"){
    apply plugin: "java"

    dependencies{
        compile project(":core")
        compile "org.lz4:lz4-java:1.4.1"
    }
}

task deployAll{
    task cleanDeployOutput{
        doFirst{
            if("${getBuildVersion()}" == "custom build" || "${getBuildVersion()}" == "") throw new IllegalArgumentException("----\n\nSET A BUILD NUMBER FIRST!\n\n----")
            if(!project.hasProperty("release")) throw new IllegalArgumentException("----\n\nSET THE RELEASE PROJECT PROPERTY FIRST!\n\n----")

            delete{
                delete "deploy/"
            }
        }
    }

    dependsOn cleanDeployOutput
    dependsOn "desktop:packrLinux64"
    dependsOn "desktop:packrWindows64"
    dependsOn "desktop:packrWindows32"
    dependsOn "desktop:packrMacOS"
    dependsOn "server:deploy"
    dependsOn "android:deploy"
}