import java.util.jar.JarEntry
import java.util.jar.JarOutputStream

plugins {
  id 'java'
  id 'com.github.johnrengelman.shadow' version '8.1.1'
}

version 'alpha-0.10.0'

sourceSets.main.java.srcDirs = ["src"]
sourceSets.test.java.srcDirs = ["test"]

"java SyncBundles.java ${version}".execute().waitForProcessOutput(System.out, System.err)

ext {
  //the build number that this mod is made for
  mindustryVersion = 'e0846b04f0'
  arcVersion = 'deacd9c98e'
  uncVersion = "2.2.0"
  //version of SDK you will be using
  minSdkAPI = 30

  sdkRoot = System.getenv("ANDROID_HOME")
}

tasks.withType(JavaCompile).configureEach {
  options.encoding = "UTF-8"

  options.compilerArgs.addAll(['--release', '8'])
}

dependencies {
  repositories {
    mavenLocal()
    mavenCentral()
    maven { url 'https://raw.githubusercontent.com/Zelaux/MindustryRepo/master/repository' }
    maven { url 'https://www.jitpack.io' }
  }

  compileOnly "com.github.Anuken.Arc:arc-core:$arcVersion"
  compileOnly "com.github.Anuken.MindustryJitpack:core:$mindustryVersion"

  compileOnly "com.github.EB-wilson.UniverseCore:core:$uncVersion"
  compileOnly "com.github.EB-wilson.UniverseCore:scenes:$uncVersion"
  compileOnly "com.github.EB-wilson.UniverseCore:markdown:$uncVersion"
  compileOnly "com.github.EB-wilson.UniverseCore:dynamilizer:$uncVersion"
  compileOnly "com.github.EB-wilson.UniverseCore:annotations:$uncVersion"

  compileOnly "com.github.EB-wilson:TooManyItems:2.5.1"

  implementation "com.github.EB-wilson.JavaDynamilizer:annotations:V1.8-A3"

  annotationProcessor "com.github.EB-wilson.UniverseCore:annotations:$uncVersion"
  annotationProcessor "com.github.EB-wilson.JavaDynamilizer:apt:V1.8-A3"

  testImplementation "com.github.Anuken.Arc:arc-core:$mindustryVersion"
  testImplementation "com.github.Anuken.MindustryJitpack:core:$mindustryVersion"
}

tasks.register('jarAndroid') {
  dependsOn shadowJar

  doLast {
    try {
      File fi = new File("$sdkRoot/platforms/")
      if (!fi.exists()) throw new RuntimeException("android SDK platfroms was not found")
      def platformRoot = fi.listFiles().sort().reverse().find { f -> new File(f, "android.jar").exists() }

      //collect dependencies needed for desugaring
      def dependencies = (configurations.compileClasspath.asList() + configurations.runtimeClasspath.asList() + [new File(platformRoot, "android.jar")]).collect { "--classpath $it.path" }.join(" ")

      try {
        System.out.println("build android dex...")

        //dex and desugar files - this requires d8 in your PATH
        "d8 $dependencies --min-api 14 --output ${rootProject.name}-android.jar ${project.archivesBaseName}-desktop.jar"
            .execute(null, new File("$buildDir/libs")).waitForProcessOutput(System.out, System.err)
      }
      catch (Throwable ignored) {
        def d8 = new File("$sdkRoot/build-tools/").listFiles().find {
          it.listFiles().any {
            it.name.contains("d8")
          } && Integer.valueOf(it.name.substring(0, 2)) >= minSdkAPI
        }.listFiles().find { it.name.contains("d8") }

        "$d8 $dependencies --min-api 14 --output ${rootProject.name}-android.jar ${project.archivesBaseName}-desktop.jar"
            .execute(null, new File("$buildDir/libs")).waitForProcessOutput(System.out, System.err)
      }
    }
    catch (Throwable ignored) {
      System.out.println("[WARNING] d8 tool or platform tools was not found, if you was installed android SDK, please check your environment variable")

      delete(
          files("${rootProject.buildDir}/libs/${rootProject.name}-android.jar")
      )

      def out = new JarOutputStream(new FileOutputStream("${rootProject.buildDir}/libs/${rootProject.name}-android.jar"))
      out.putNextEntry(new JarEntry("non-androidMod.txt"))
      StringReader reader = new StringReader(
          "this mod is don't have classes.dex for android, please consider recompile with a SDK or run this mod on desktop only"
      )

      int r
      while ((r = reader.read()) != -1) {
        out.write(r)
        out.flush()
      }
      out.close()
    }
  }
}

shadowJar {
  archiveFileName = "${project.archivesBaseName}-desktop.jar"

  from(rootDir) {
    include "mod.hjson"
    include "icon.png"
    include "contributors.hjson"
  }

  from("assets/") {
    include "**"
  }
}

tasks.register('deploy', Jar) {
  dependsOn jarAndroid
  dependsOn shadowJar
  archiveFileName = "${project.archivesBaseName}.jar"

  from {
    [
        zipTree("$buildDir/libs/${project.archivesBaseName}-desktop.jar"),
        zipTree("$buildDir/libs/${project.archivesBaseName}-android.jar")
    ]
  }

  doLast {
    if (project.properties.get("modOutputDir") != null && !project.properties.get("modOutputDir").isEmpty()) {
      copy {
        into("$modOutputDir/")
        from("$buildDir/libs/${project.archivesBaseName}.jar")
      }
    }
  }
}

tasks.register('deployDesktop', Jar) {
  dependsOn shadowJar
  archiveFileName = "${project.archivesBaseName}.jar"

  from {
    [zipTree("$buildDir/libs/${project.archivesBaseName}-desktop.jar")]
  }

  doLast {
    if (project.properties.get("modOutputDir") != null && !project.properties.get("modOutputDir").isEmpty()) {
      copy {
        into("$modOutputDir/")
        from("$buildDir/libs/${project.archivesBaseName}.jar")
      }
    }
  }
}

tasks.register('debugMod', JavaExec) {
  dependsOn classes
  dependsOn deployDesktop

  main = "-jar"
  args = [
      project.properties.get("debugGamePath"),
      "-debug"
  ]
}
