//
// NOTICE: This Gradle build script is COMPLETELY CUSTOM and necessary for PickHaxe to run.
//         It automatically gets replaced EVERY BUILD.
//         If you need a feature, please open an issue on GitHub.
// 

buildscript {
  println "Java: ${System.getProperty('java.version')}, JVM: ${System.getProperty('java.vm.version')} (${System.getProperty('java.vendor')}), Arch: ${System.getProperty('os.arch')}"

  println "PickHaxe: ${System.getProperty('pickhaxe.version')}, Loader: ${System.getProperty('pickhaxe.loader.current')}"

  println "Task: ${System.getProperty('pickhaxe.task')}"

  ext.FORGEGRADLE_VERSION = System.getProperty('pickhaxe.gradle.plugins.forgegradle')
} 

// Reference all Gradle plugins, with versions.
plugins {
  //
  // Forge
  //
  id 'net.minecraftforge.gradle' version "${FORGEGRADLE_VERSION}" apply false
  id 'net.minecraftforge.gradle.mcp' version "${FORGEGRADLE_VERSION}" apply false
  id 'net.minecraftforge.gradle.patcher' version "${FORGEGRADLE_VERSION}" apply false
  id 'org.parchmentmc.librarian.forgegradle' version '1.+' apply false

  // 
  // Fabric
  //
  id 'fabric-loom' version '1.1-SNAPSHOT' apply false

  //
  // Common
  //
  id 'maven-publish'
}

// Select the Gradle plugin based on the loader.
switch(System.getProperty('pickhaxe.loader.current')) {
  case 'forge':
    apply plugin: 'net.minecraftforge.gradle'
    apply plugin: 'org.parchmentmc.librarian.forgegradle'
    break
  case 'fabric':
    apply plugin: 'fabric-loom'
    break
  case null:
    throw new Exception("PickHaxe: Missing loader")
  default:
    throw new Exception("PickHaxe: Unknown loader: ${System.getProperty('pickhaxe.loader.current')}")
}

switch(System.getProperty('pickhaxe.java.version')) {
  case '1.8':
    switch(System.getProperty('pickhaxe.loader.current')) {
      case 'fabric':
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
        break;
      case 'forge':
        // Nothing
        break;
      default:
        throw new Exception("PickHaxe: Unknown loader: ${System.getProperty('pickhaxe.loader.current')}")
    }
  case '16':
    switch(System.getProperty('pickhaxe.loader.current')) {
      case 'fabric':
        sourceCompatibility = JavaVersion.VERSION_16
        targetCompatibility = JavaVersion.VERSION_16
        break;
      case 'forge':
        // Nothing
        break;
      default:
        throw new Exception("PickHaxe: Unknown loader: ${System.getProperty('pickhaxe.loader.current')}")
    }
  case '17':
    switch(System.getProperty('pickhaxe.loader.current')) {
      case 'fabric':
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
        break;
      case 'forge':
        java.toolchain.languageVersion = JavaLanguageVersion.of(17)
        break;
      default:
        throw new Exception("PickHaxe: Unknown loader: ${System.getProperty('pickhaxe.loader.current')}")
    }
}

archivesBaseName = System.getProperty('pickhaxe.mod.id')
version = System.getProperty('pickhaxe.mod.version')
group = System.getProperty('pickhaxe.mod.parentPackage')

if (System.getProperty('pickhaxe.loader.current').equals('forge')) {
  minecraft {
    switch(System.getProperty('pickhaxe.mappings.current')) {
      case 'official':
      case 'mojmaps':
      case 'mojang':
        mappings channel: 'official', version: System.getProperty('pickhaxe.minecraft.version')
        break;
      case 'parchment':
        mappings channel: 'parchment', version: System.getProperty('pickhaxe.mappings.parchment.version') + '-' + System.getProperty('pickhaxe.minecraft.version')
        break;
      case 'yarn':
        if (System.getProperty('pickhaxe.minecraft.snapshot')) {
          mappings "net.fabricmc:yarn:23w13a_or_b+build.2:v2"
        } else {
          mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
        }
        break;
    }

    runs {
      client {
          taskName 'runClient'
          workingDirectory project.file('../run/client')

          // The main launch class for Forge (Dev)
          main 'cpw.mods.bootstraplauncher.BootstrapLauncher'

          // Some recommended debug properties.
          property 'forge.logging.markers', 'REGISTRIES'
          property 'forge.logging.console.level', 'debug'
          property 'forge.enabledGameTestNamespaces', 'examplemod'
          
          client true

          // arg
          // jvmArg

          //mods.register(System.getProperty('pickhaxe.mod.id')).configure {
          //  source sourceSets.main
          //}
      }
    }

    accessTransformer = file('resources/META-INF/accesstransformer.cfg')
  }
}

repositories {
  mavenCentral()
  gradlePluginPortal()
  // Fabric plugins and API libraries
  maven { url = 'https://maven.fabricmc.net' }
  // Forge plugins and API libraries
  maven { url = 'https://maven.minecraftforge.net' }
  // ParchmentMC Mappings
  maven { url = 'https://maven.parchmentmc.org' }
}

configurations {
  shade
  implementation.extendsFrom shade
}

dependencies {
  switch(System.getProperty('pickhaxe.loader.current')) {
    case 'forge':
      minecraft "net.minecraftforge:forge:${System.getProperty('pickhaxe.minecraft.version')}-${System.getProperty('pickhaxe.loader.forge.apiVersion')}"

      if (System.getProperty('pickhaxe.task').equals('runClient')) {
        // Add JARs to the classpath for the runClient task.

        // Run configurations use the dev JAR.
        // You can use fg.deobf() to deobfuscate an obfuscated JAR before including.
        println "../build/${System.getProperty('pickhaxe.loader.current')}/${System.getProperty('pickhaxe.minecraft.version')}/${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}-dev.jar"
        runtimeOnly files("../build/${System.getProperty('pickhaxe.loader.current')}/${System.getProperty('pickhaxe.minecraft.version')}/${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}-dev.jar")
      }
      break;
    case 'fabric':
      // To change the versions see the gradle.properties file
	    minecraft "com.mojang:minecraft:${System.getProperty('pickhaxe.minecraft.version')}"

      // Configure mappings for the Fabric loader.
      switch(System.getProperty('pickhaxe.mappings.current')) {
        case 'official':
        case 'mojmaps':
        case 'mojang':
          mappings loom.officialMojangMappings()
          break;
        case 'parchment':
          mappings loom.layered() {
              officialMojangMappings()
              parchment("org.parchmentmc.data:${System.getProperty('pickhaxe.mappings.parchment.maven')}@zip")
          }
          break;
        case 'yarn':
          mappings "net.fabricmc:yarn:${System.getProperty('pickhaxe.mappings.yarn.version')}"
          break;
      }

	    modImplementation "net.fabricmc:fabric-loader:${System.getProperty('pickhaxe.loader.fabric.loaderVersion')}"

	    modImplementation "net.fabricmc.fabric-api:fabric-api:${System.getProperty('pickhaxe.loader.fabric.apiVersion')}"

	    //modImplementation "net.fabricmc.fabric-api:fabric-api-deprecated:${project.fabric_version}"
      break;

    default:
      throw new Exception("PickHaxe: Unknown loader: ${System.getProperty('pickhaxe.loader.current')}")
  }
}

tasks.withType(JavaCompile).configureEach {
	// Minecraft 1.18 (1.18-pre2) upwards uses Java 17.
	it.options.release = System.getProperty('pickhaxe.java.version') == '17' ? 17 : 8
  options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}

sourceSets {
  // Haxe generates Java source in a different spot.
  main.java.srcDirs = ['java/src']
  // LOL we can just reuse the resources folder.
  // main.resources.srcDirs = ['resources']
}

task copyDependencies(type: Copy) {
  from configurations.compileClasspath
  into "$buildDir/minecraft/${System.getProperty('pickhaxe.loader.current')}/${System.getProperty('pickhaxe.minecraft.version')}/"
}
copyDependencies.group = 'PickHaxe'
copyDependencies.description = 'Copies all runtime dependencies to a place where they can be easily referenced by Haxe.'

task copyBuildArtifacts(type: Copy) {
  def buildFile = file("$buildDir/libs/${archivesBaseName}-${version}.jar")
  from buildFile
  into "../build/${System.getProperty('pickhaxe.loader.current')}/${System.getProperty('pickhaxe.minecraft.version')}/"
}
copyBuildArtifacts.group = 'PickHaxe'
copyBuildArtifacts.description = 'Copies the built Minecraft mod JAR to a place where it can be easily accessed.'

// Modify the `build` task to include additional metadata in the MANIFEST.
tasks.jar {
  archiveClassifier = 'slim'
  manifest {
    attributes(
      'PickHaxe-Library-Version': System.getProperty('pickhaxe.version'),
      'PickHaxe-Haxe-Version': System.getProperty('pickhaxe.haxe.version'),
      'PickHaxe-Minecraft-Version': System.getProperty('pickhaxe.minecraft.version'),
      'PickHaxe-Loader': System.getProperty('pickhaxe.loader.current'),
      'PickHaxe-Mod-Metadata-Id': System.getProperty('pickhaxe.mod.id'),
      'PickHaxe-Mod-Metadata-Version': System.getProperty('pickhaxe.mod.version'),

      // "Specification-Title"     : "examplemod",
      // "Specification-Vendor"    : "examplemodsareus",
      // "Specification-Version"   : "1", // We are version 1 of ourselves
      // "Implementation-Title"    : project.name,
      // "Implementation-Version"  : project.jar.archiveVersion,
      // "Implementation-Vendor"   : "examplemodsareus",
      "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
    )
  }
}

if (System.getProperty('pickhaxe.loader.current').equals('fabric') && System.getProperty('pickhaxe.haxe.jvm').equals('true')) {
  remapJar {
    input = file("../build/fabric/${System.getProperty('pickhaxe.minecraft.version')}/${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}-dev.jar")
    archiveFileName = "../../../build/fabric/${System.getProperty('pickhaxe.minecraft.version')}/${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}.jar"
  }
} else if (System.getProperty('pickhaxe.loader.current').equals('forge') && System.getProperty('pickhaxe.haxe.jvm').equals('true')
  && (System.getProperty('pickhaxe.task').equals('reobfSourcesJar') || System.getProperty('pickhaxe.task').equals('reobfShadowSourcesJar')|| System.getProperty('pickhaxe.task').equals('shadowSourcesJar'))) {
  task sourcesJar(type: Jar) {
    from zipTree("../build/forge/${System.getProperty('pickhaxe.minecraft.version')}/${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}-dev.jar")
  }

  reobf {
    sourcesJar {
      finalizedBy('copyReobfSourcesJar')
    }
  }

  task copyReobfSourcesJar(type: Copy) {
    from("$buildDir/reobfSourcesJar") {
      rename "output.jar", "${System.getProperty('pickhaxe.mod.id')}-${System.getProperty('pickhaxe.mod.version')}.jar"
    }
    exclude '**/*.txt'
    into "../build/forge/${System.getProperty('pickhaxe.minecraft.version')}/"
  }
}

if (System.getProperty('pickhaxe.loader.current').equals('fabric')) {
  loom {
    accessWidenerPath = file("resources/META-INF/${System.getProperty('pickhaxe.mod.id')}.accesswidener")
  }
}


if (System.getProperty('pickhaxe.loader.current').equals('forge')) {
  jar.finalizedBy('reobfJar')

  // Disable additional resource processing for the runClient task.
  processResources.onlyIf { 
    !System.getProperty('pickhaxe.task').equals('runClient')
  }
}

// Run the copyBuildArtifacts task after the build task.
build.finalizedBy(copyBuildArtifacts)
