buildscript {
    repositories {
        maven { url = 'https://maven.minecraftforge.net' }
        maven {
            url = 'https://repo.spongepowered.org/repository/maven-public/'
            content { includeGroup "org.spongepowered" }
        }
        mavenCentral()
    }
    dependencies {
        classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
        classpath 'org.spongepowered:mixingradle:0.7-SNAPSHOT'
    }
}

plugins {
    id "com.modrinth.minotaur" version "2.+"
    // It's safest to have this on 2.+ to get the latest features and
    // bug fixes without having to worry about breaking changes.
}

apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'org.spongepowered.mixin'

archivesBaseName = getArtifactID("forge")

println "asdf"

// Adds KFF as dependency and Kotlin libs to the runtime classpath
// If you already know how to add the Kotlin plugin to Gradle, this is the only line you need for KFF
apply from: "https://raw.githubusercontent.com/thedarkcolour/KotlinForForge/site/thedarkcolour/kotlinforforge/gradle/kff-${kotlinForForgeVersion}.gradle"

minecraft {
    mappings channel: 'official', version: minecraftVersion
    accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')

    if (project.hasProperty('forge_ats_enabled') && project.findProperty('forge_ats_enabled').toBoolean()) {
        // This location is hardcoded in Forge and can not be changed.
        // https://github.com/MinecraftForge/MinecraftForge/blob/be1698bb1554f9c8fa2f58e32b9ab70bc4385e60/fmlloader/src/main/java/net/minecraftforge/fml/loading/moddiscovery/ModFile.java#L123
        accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
        project.logger.debug('Forge Access Transformers are enabled for this project.')
    }

    runs {
        client {
            workingDirectory project.file('run')
            ideaModule "${rootProject.name}.${project.name}.main"
            property 'mixin.env.remapRefMap', 'true'
            property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"
            mods {
                create(modID) {
                    source sourceSets.main
                    source project(":Common").sourceSets.main
                }
            }
        }

        server {
            workingDirectory project.file('run')
            ideaModule "${rootProject.name}.${project.name}.main"
            property 'mixin.env.remapRefMap', 'true'
            property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"
            mods {
                create(modID) {
                    source sourceSets.main
                    source project(":Common").sourceSets.main
                }
            }
        }

        // This run config launches GameTestServer and runs all registered gametests, then exits.
        // By default, the server will crash when no gametests are provided.
        // The gametest system is also enabled by default for other run configs under the /test command.
        gameTestServer {
            workingDirectory project.file('run')
            ideaModule "${rootProject.name}.${project.name}.main"
            property 'mixin.env.remapRefMap', 'true'
            property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"

            // Recommended logging data for a userdev environment
            // The markers can be added/remove as needed separated by commas.
            // "SCAN": For mods scan.
            // "REGISTRIES": For firing of registry events.
            // "REGISTRYDUMP": For getting the contents of all registries.
            property 'forge.logging.markers', 'REGISTRIES'

            // Recommended logging level for the console
            // You can set various levels here.
            // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
            property 'forge.logging.console.level', 'debug'

            // Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
            property 'forge.enabledGameTestNamespaces', 'hexucasting'

            mods {
                create(modID) {
                    source sourceSets.main
                    source sourceSets.test
                    source project(":Common").sourceSets.test
                }
            }
        }

        // We have to have a dummy data run to be parented from
        data {}

        xplatDatagen {
            parent minecraft.runs.data

            workingDirectory project.file('run')
            ideaModule "${rootProject.name}.${project.name}.main"
            args '--mod', modID, '--all', '--output', file('../Common/src/generated/resources/'), '--existing', file('../Common/src/main/resources/')
            property 'mixin.env.remapRefMap', 'true'
            property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"
            property 'hexucasting.xplat_datagen', 'true'
            mods {
                create(modID) {
                    source sourceSets.main
                    source project(":Common").sourceSets.main
                }
            }
        }

        forgeDatagen {
            parent minecraft.runs.data

            workingDirectory project.file('run')
            ideaModule "${rootProject.name}.${project.name}.main"
            args '--mod', modID, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
            property 'mixin.env.remapRefMap', 'true'
            property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"
            property 'hexucasting.forge_datagen', 'true'
            mods {
                create(modID) {
                    source sourceSets.main
                    source project(":Common").sourceSets.main
                }
            }
        }
    }
}

repositories {
    mavenCentral()
    // Put repositories for dependencies here
    // ForgeGradle automatically adds the Forge maven and Maven Central for you

    // If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
     flatDir {
         dir 'libs'
     }

    maven {
        // location of the maven that hosts JEI files
        name = "Progwml6 maven"
        url = "https://dvs1.progwml6.com/files/maven/"
    }
    maven {
        // location of a maven mirror for JEI files, as a fallback
        name = "ModMaven"
        url = "https://modmaven.dev"
    }
}

dependencies {
    // Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
    // that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
    // The userdev artifact is a special name and will get all sorts of transformations applied to it.
    minecraft "net.minecraftforge:forge:${minecraftVersion}-${forgeVersion}"
    compileOnly project(":Common")

    annotationProcessor 'org.spongepowered:mixin:0.8.5:processor'

    compileOnly fg.deobf("at.petra-k.paucal:paucal-forge-$minecraftVersion:$paucalVersion")
    runtimeOnly fg.deobf("at.petra-k.paucal:paucal-forge-$minecraftVersion:$paucalVersion")
    compileOnly fg.deobf("${modID}:hexcasting-forge-$minecraftVersion:$hexcastingVersion")
    runtimeOnly fg.deobf("${modID}:hexcasting-forge-$minecraftVersion:$hexcastingVersion")

    compileOnly fg.deobf("vazkii.patchouli:Patchouli:$minecraftVersion-$patchouliVersion")
    runtimeOnly fg.deobf("vazkii.patchouli:Patchouli:$minecraftVersion-$patchouliVersion")

    // Testing dependencies:
    testCompileOnly project(":Common")

    testAnnotationProcessor 'org.spongepowered:mixin:0.8.5:processor'

    testCompileOnly fg.deobf("at.petra-k.paucal:paucal-forge-$minecraftVersion:$paucalVersion")
    testRuntimeOnly fg.deobf("at.petra-k.paucal:paucal-forge-$minecraftVersion:$paucalVersion")
    testCompileOnly fg.deobf("${modID}:hexcasting-forge-$minecraftVersion:$hexcastingVersion")
    testRuntimeOnly fg.deobf("${modID}:hexcasting-forge-$minecraftVersion:$hexcastingVersion")
    testCompileOnly fg.deobf("vazkii.patchouli:Patchouli:$minecraftVersion-$patchouliVersion")
    testRuntimeOnly fg.deobf("vazkii.patchouli:Patchouli:$minecraftVersion-$patchouliVersion")

    testCompileOnly 'org.junit.jupiter:junit-jupiter-api:5.9.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
}

mixin {
    add sourceSets.main, "hexucasting.mixins.refmap.json"
    add sourceSets.test, "hexucasting.test.mixins.refmap.json"
    config "hexucastingplat.mixins.json"
    config "hexucasting_forge.mixins.json"
}

tasks.withType(JavaCompile) {
    source(project(":Common").sourceSets.main.allSource)
}
compileKotlin {
    source(project(":Common").sourceSets.main.kotlin)
}
compileTestKotlin {
    source(project(":Common").sourceSets.test.kotlin)
}

// This task is here for debugging purposes, running it tells you what directories each sourceSet is setup to look at.
task printSourceSetInformation(){
    doLast{
        sourceSets.each { srcSet ->
            println "["+srcSet.name+"]"
            print "-->Java Source directories: "+srcSet.allJava.srcDirs+"\n"
            print "-->Kotlin Source directories: "+srcSet.kotlin.srcDirs+"\n"
            print "-->Resource directories: "+srcSet.resources.srcDirs+"\n"
            print "-->Output directories: "+srcSet.output.classesDirs.files+"\n"
//            print "-->Compile classpath:\n"
//            srcSet.compileClasspath.files.each {
//                print "  "+it.path+"\n"
//            }
            println ""
        }
    }
}


// https://discord.com/channels/313125603924639766/733055378371117127/980968358658838540
// > It won't generate a refmap if there are no changes source files
// > Since the last build
// > Gradle task execution avoidance breaks it that way
// > At one point i got it to work reliably but forcing some specific task to always run i just don't remember the syntax and which task it was
// > It might have been compileJava
build {
    println "Forcing re-compile of Java to include refmap"
    tasks.withType(JavaCompile) {
        outputs.upToDateWhen { false }
    }
    compileKotlin {
        outputs.upToDateWhen { false }
    }
}

sourceSets {
    main.resources.srcDirs += ['src/generated/resources', '../Common/src/generated/resources']
    test.resources.srcDirs += ['src/generated/resources', '../Common/src/generated/resources', 'src/main/resources', '../Common/src/main/resources']
    main.kotlin.srcDirs += 'src/main/java'
    test.kotlin.srcDirs += 'src/main/java'
}

processResources {
    from project(":Common").sourceSets.main.resources
    inputs.property "version", project.version

    filesMatching("mods.toml") {
        expand "version": project.version
    }
}

processTestResources {
    from project(":Common").sourceSets.test.resources
    inputs.property "version", project.version

    filesMatching("mods.toml") {
        expand "version": project.version
    }
}

def loadProperties = { filename ->
    def properties = new Properties()
    rootProject.file(filename).withInputStream {
        properties.load(it)
    }
    return properties
}

/**
 * To setup automatic modrinth exporting, get your API key from the modrinth website and place it in a
 * file in the root project directory called keys.properties
 * e.g.
 * MODRINTH_TOKEN=exampletoken
 * Then, uncomment the modrinth blocks in every build.gradle. When you run the modrinth build task
 * in the base project task space, it will upload both Forge and Fabric versions of the mod to
 * modrinth automatically, with the changelog from the changelog.md file in the base project directory.
 */
//modrinth {
//    token = loadProperties("keys.properties").MODRINTH_TOKEN
//    projectId = "$modID" // This can be the project ID or the slug. Either will work!
//    versionNumber = "$modVersion" // You don't need to set this manually. Will fail if Modrinth has this version already
//    versionName = "$modVersion-forge"
//    changelog = rootProject.file("changelog.md").text
//    versionType = "release" // This is the default -- can also be `beta` or `alpha`
//    uploadFile = jar // With Loom, this MUST be set to `remapJar` instead of `jar`!
//    gameVersions = ["1.19.2"] // Must be an array, even with only one version
//    loaders = ["forge"] // Must also be an array - no need to specify this if you're using Loom or ForgeGradle
//    dependencies { // A special DSL for creating dependencies
//        // scope.type
//        // The scope can be `required`, `optional`, `incompatible`, or `embedded`
//        // The type can either be `project` or `version`
//        required.project "hex-casting" // Creates a new required dependency on Hex Casting
//        required.project "paucal"
//        required.project "patchouli"
//        required.project "kotlin-for-forge"
//    }
//}

jar.finalizedBy('reobfJar')
setupJar(this)
