import org.teavm.gradle.api.OptimizationLevel

buildscript {
    dependencies {
        classpath files("src/teavmc-classpath/resources")
    }
}

plugins {
    id "java"
    id "eclipse"
    id "org.teavm" version "0.9.2"
}

sourceSets {
    main {
        java {
            srcDirs(
                "src/main/java",
                "src/game/java",
               	"src/protocol-game/java",
                "src/protocol-relay/java",
                "src/teavm/java",
                "src/teavm-boot-menu/java"
            )
        }
    }
    desktop {
        java {
            srcDirs(
                "src/main/java",
                "src/game/java",
                "src/protocol-game/java",
                "src/protocol-relay/java",
                "src/lwjgl/java"
            )
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    teavm(teavm.libs.jso)
    teavm(teavm.libs.jsoApis)
    compileOnly "org.teavm:teavm-core:0.9.2" // workaround for a few hacks

    desktopImplementation fileTree("desktopRuntime/eclipseProject/deps_fix")
}

def folder = "javascript"
def name = "classes.js"

teavm.js {
    compileJava.options.encoding = "UTF-8"
    obfuscated = true
    sourceMap = true
    targetFileName = "../" + name
    optimization = OptimizationLevel.AGGRESSIVE // Change to "AGGRESSIVE" for release
    outOfProcess = false
    fastGlobalAnalysis = false
    processMemory = 512
    entryPointName = "main"
    mainClass = "net.lax1dude.eaglercraft.v1_8.internal.teavm.MainClass"
    outputDir = file(folder)
    properties = [ "java.util.TimeZone.autodetect": "true" ]
    debugInformation = false
}

tasks.named("generateJavaScript") {
    doLast {
        delete file(folder + "/js")

        // NOTE: This step may break at any time, and is not required for 99% of browsers

        def phile = file(folder + "/" + name)
        def dest = phile.getText("UTF-8")
        def i = dest.substring(0, dest.indexOf("=\$rt_globals.Symbol('jsoClass');")).lastIndexOf("let ")
        dest = dest.substring(0, i) + "var" + dest.substring(i + 3)
        def j = dest.indexOf("function(\$rt_globals,\$rt_exports){")
        dest = dest.substring(0, j + 34) + "\n" + file("desktopRuntime/resources/ES6ShimScript.txt").getText("UTF-8") + "\n" + dest.substring(j + 34)
        phile.write(dest, "UTF-8")
    }
}

tasks.register('runclient', JavaExec) {
    classpath = sourceSets.desktop.compileClasspath
    group = "EaglercraftX"
    description = "Runs the client"
    classpath sourceSets.desktop.runtimeClasspath
    jvmArgs '-Djava.library.path=.'
    if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        jvmArgs '-Djava.library.path=. -XstartOnFirstThread'
    }

    args = ["hide-renderdoc"]

    workingDir "./desktopRuntime"
    main 'net.lax1dude.eaglercraft.v1_8.internal.lwjgl.MainClass'
}