plugins {
  id 'java'
  id 'dev.fiki.forgehax.mapper'
  alias libs.plugins.forgegradle
  alias libs.plugins.gitgradle
}

ext {
  minecraftVersion = libs.versions.minecraft.get()
  forgeVersion = libs.versions.forge.get()
}

final git = versionDetails()

group 'dev.fiki.forgehax'
version "${git.lastTag.substring(1)}.r${git.commitDistance}_${git.gitHash}"
archivesBaseName = "ForgeHax_${minecraftVersion}"

final isCiBuilding = System.getenv().get('CI') == 'true'

if (isCiBuilding) {
  logger.warn 'CI build. Certain modules will be omitted from this build'
}

java {
  toolchain {
    languageVersion = JavaLanguageVersion.of(8)
  }
}

configurations {
  all {
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
  }
}

sourceSets {
  api {
    compileClasspath += main.compileClasspath
  }

  main {
    if (isCiBuilding) {
      java {
        exclude 'dev/fiki/forgehax/main/mods/ForgeModListSpoofer.java'
      }
    }
    compileClasspath += api.output
  }
}

minecraft {
  mappings channel: 'official', version: minecraftVersion

  runs {
    client {
      workingDirectory project.file('run')

      property 'forge.logging.console.level', 'info'
      property 'forgehax.logging.level', 'debug'

      mods {
        ForgeHax {
          sources sourceSets.main
        }
      }
    }
  }
}

mapper {
  targets sourceSets.main, sourceSets.test
}

dependencies {
  minecraft libs.minecraftforge

  compileOnly libs.lombok
  annotationProcessor libs.lombok

  testCompileOnly libs.lombok
  testAnnotationProcessor libs.lombok
  testImplementation libs.bundles.jupiter
  testImplementation libs.assertj
}

compileJava {
  // this will allow use to read a constructors parameter names at runtime
  options.compilerArgs << '-parameters'
}

test {
  useJUnitPlatform()
}

jar {
  manifest {
    attributes([
        "Specification-Title"     : "ForgeHax",
        "Specification-Vendor"    : "fikidev",
        "Specification-Version"   : "1",
        "Implementation-Title"    : project.name,
        "Implementation-Version"  : project.version,
        "Implementation-Vendor"   : "fikidev",
        "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
    ])
  }
}

static def getForgeMajorVersion(String version) {
  final dash = version.indexOf('-')
  return version.substring(dash + 1, version.indexOf('.', dash))
}

def getContributors(String apiUrl) {
  try {
    final url = new URL(apiUrl)
    final json = new groovy.json.JsonSlurper().parseText(url.text)
    return String.join(', ', json.collect { it.login })
  } catch (Throwable t) {
    logger.warn("Failed to get contributors from GitHub API! Defaulting to hardcoded users...")
    logger.debug(t.getMessage(), t)
    return 'fr1kin, BabbaJ, 0x22'
  }
}

processResources {
  from 'logo.png'

  filesMatching('**/mods.toml') {
    //noinspection UnnecessaryQualifiedReference
    it.filter org.apache.tools.ant.filters.ReplaceTokens, tokens: [
        'forgehax.version'      : project.version as String,
        'forgehax.forge.version': getForgeMajorVersion(forgeVersion), // only extract major version
        'forgehax.issue.tracker': 'https://github.com/fr1kin/ForgeHax/issues',
        'forgehax.update.url'   : 'TODO',
        'forgehax.url'          : 'fiki.dev',
        'forgehax.logo.file'    : 'logo.png',
        'forgehax.credits'      : 'Rain#4705 for the logo',
        'forgehax.authors'      : getContributors('https://api.github.com/repos/fr1kin/ForgeHax/contributors'),
        'forgehax.description'  : 'Hax 4 Forge'
    ]
  }
}

task setGameDir() {
  // Check if custom gamedir has been passed, if not use default ones per platform
  if (!project.hasProperty("gameDir")) {
    if (org.gradle.internal.os.OperatingSystem.current().isWindows()) {
      project.ext.gameDir = System.getenv("APPDATA") + "/.minecraft"
    } else if (org.gradle.internal.os.OperatingSystem.current().isMacOsX()) {
      project.ext.gameDir = System.properties["user.home"] + "/Library/Application Support/minecraft"
    } else {
      project.ext.gameDir = System.properties["user.home"] + "/.minecraft"
    }
  }
}

task copyJar(type: DefaultTask, dependsOn: [setGameDir]) {
  onlyIf { !isCiBuilding }
  doFirst {
    if (file(project.ext.gameDir).exists()) {
      final files = { directory, filter, closure ->
        new File(directory).eachFileMatch(filter, closure)
      }

      final mods = "${project.ext.gameDir}/mods"

      project.copy {
        // delete previous ForgeHax jars
        files(mods, ~/ForgeHax-.*\.jar/) { file ->
          file.delete()
        }

        from project.jar
        into mods
      }
    }
  }
}

task createGitHubActionsVars() {
  onlyIf { isCiBuilding }
  doFirst {
    println "::set-output name=mcversion::${minecraftVersion}"
    println "::set-output name=version::${project.version}"
    println "::set-output name=jar::${jar.archiveFileName.get()}"
  }
}

build {
  finalizedBy copyJar, createGitHubActionsVars
}
