plugins {
    id 'fabric-loom' version '1.7-SNAPSHOT'
    id 'maven-publish'
    id 'me.fallenbreath.yamlang' version '1.3.1'
    id "me.modmuss50.mod-publish-plugin" version "0.4.4"
    id "com.diffplug.spotless" version "7.0.2"
}

version = project.mod_version
group = project.maven_group

base {
    archivesName = project.archives_base_name
}

repositories {
    // Add repositories to retrieve artifacts from in here.
    // You should only use this when depending on other mods because
    // Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
    // See https://docs.gradle.org/current/userguide/declaring_repositories.html
    // for more information about repositories.
    mavenCentral()

    maven {
        name = "Modrinth"
        url = "https://api.modrinth.com/maven"
        content {
            includeGroup "maven.modrinth"
        }
    }

    maven {
        url "https://maven.enjarai.dev/releases"
    }
    maven {
        url "https://maven.enjarai.dev/mirrors"
    }
}

loom {
    accessWidenerPath.set(file("src/main/resources/trickster.accesswidener"))
    splitEnvironmentSourceSets()

    mods {
        "trickster" {
            sourceSet sourceSets.main
            sourceSet sourceSets.client
        }
    }

    runs {
        client_mixin {
            client()
            ideConfigGenerated true
            name = "Minecraft Client - (Mixin Swap)"
            source sourceSets.main
            source sourceSets.client
            vmArg "-Dmixin.debug.export=true"

            try {
                afterEvaluate {
                    def mixinDep = this.configurations.compileClasspath
                            .allDependencies
                            .findAll { it.name == "sponge-mixin" }
                            .first()

                    if (mixin != null) {
                        def mixinPath = this.configurations.compileClasspath.files(mixinDep).first().path;

                        println(mixinPath)

                        vmArg("-javaagent:\"${mixinPath}\"")

                        println("[Info]: Mixin Hotswap Run should be working")
                    } else {
                        println("[Warning]: Unable to locate file path for Mixin Jar, HotSwap Run will not work!!!")
                    }
                }
            } catch (Exception e) {
                println("[Error]: MixinHotswap Run had a issue!")
                e.printStackTrace()
            }
        }
    }
}

fabricApi {
    configureDataGeneration()
}

dependencies {
    // To change the versions see the gradle.properties file
    minecraft "com.mojang:minecraft:${property('deps.minecraft')}"
    mappings "net.fabricmc:yarn:${property('deps.yarn')}:v2"
    modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"

    // Fabric API. This is technically optional, but you probably want it anyway.
    modImplementation "net.fabricmc.fabric-api:fabric-api:${property('deps.fabric-api')}"

    annotationProcessor modApi("io.wispforest:owo-lib:${property('deps.owo-lib')}")
    include "io.wispforest:owo-sentinel:${property('deps.owo-lib')}"

    modApi "io.wispforest:lavender:${property('deps.lavender')}"
//    implementation "io.wispforest:endec:0.1.0-pre.8"
    include modLocalRuntime("io.wispforest.lavender-md:owo-ui:0.1.2+1.21")

    include implementation(api("io.vavr:vavr:0.10.5"))

    modApi("nl.enjarai:cicada-lib:${property('deps.cicada')}")

    include modApi("org.ladysnake.cardinal-components-api:cardinal-components-base:${property('deps.cardinal-components-api')}")
    include modApi("org.ladysnake.cardinal-components-api:cardinal-components-chunk:${property('deps.cardinal-components-api')}")
    include modApi("org.ladysnake.cardinal-components-api:cardinal-components-world:${property('deps.cardinal-components-api')}")
    include modApi("org.ladysnake.cardinal-components-api:cardinal-components-scoreboard:${property('deps.cardinal-components-api')}")
    include modApi("org.ladysnake.cardinal-components-api:cardinal-components-entity:${property('deps.cardinal-components-api')}")

    modCompileOnly modLocalRuntime("com.terraformersmc:modmenu:${property('deps.modmenu')}")
    modClientCompileOnly modLocalRuntime("maven.modrinth:sodium:${property('deps.sodium')}")

    modApi("io.wispforest:accessories-fabric:${property('deps.accessories')}")

    // Optional compat
    modCompileOnly modLocalRuntime("maven.modrinth:transmog:${property('deps.transmog')}")

    modClientCompileOnly modLocalRuntime("mod.master_bw3:coleus:${property('deps.coleus')}")
    compileOnly "com.j2html:j2html:${property('deps.j2html')}"
}

processResources {
    inputs.property "version", project.version

    filesMatching("fabric.mod.json") {
        expand "version": project.version
    }
}

tasks.withType(JavaCompile).configureEach {
    it.options.release = 21
}

java {
    // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
    // if it is present.
    // If you remove this line, sources will not be generated.
    withSourcesJar()

    sourceCompatibility = JavaVersion.VERSION_21
    targetCompatibility = JavaVersion.VERSION_21
}

jar {
    from("LICENSE") {
        rename { "${it}_${project.base.archivesName.get()}" }
    }
}

yamlang {
    targetSourceSets = [sourceSets.main]
    inputDir = "assets/trickster/lang"
}

compileJava.dependsOn 'spotlessApply'
spotless {
    ratchetFrom 'origin/master'
    encoding 'UTF-8'

    format 'misc', {
        target '*.gradle', '.gitattributes', '.gitignore', 'shell.nix'

        trimTrailingWhitespace()
        leadingTabsToSpaces()
        endWithNewline()
    }

    java {
        toggleOffOn()
        removeUnusedImports()
        eclipse('4.26').configFile('eclipse-prefs.properties')
    }
}

// configure the maven publication
publishing {
    repositories {
        maven {
            name = "enjaraiMaven"
            url = "https://maven.enjarai.dev/releases"
            credentials(PasswordCredentials)
            authentication {
                basic(BasicAuthentication)
            }
        }
    }

    publications {
        mavenJava(MavenPublication) {
            groupId = group
            artifactId = archivesBaseName
            version = version

            from components.java
        }
    }
}

publishMods {
    file = remapJar.archiveFile
    displayName = "${property('mod_version')} for ${property('deps.minecraft')}"
    version = project.version
    changelog = getRootProject().file("CHANGELOG.md").text
    type = BETA
    modLoaders.add("fabric")

    def min = property('publish_target_min')
    def max = property('publish_target_max')

    if (providers.gradleProperty('enjaraiModrinthToken').present) {
        modrinth {
            projectId = property('mod_modrinth')
            accessToken = providers.gradleProperty('enjaraiModrinthToken').get()

            if (min == max) {
                minecraftVersions.add(min)
            } else {
                minecraftVersionRange {
                    start = min
                    end = max
                }
            }

            requires {
                slug = "fabric-api"
            }
            requires {
                slug = "cicada"
            }
            requires {
                slug = "owo-lib"
            }
            requires {
                slug = "lavender"
            }
            requires {
                slug = "accessories"
            }
            embeds {
                slug = "cardinal-components-api"
            }
        }
    }

    if (providers.gradleProperty('enjaraiCurseforgeToken').present) {
        curseforge {
            projectId = property('mod_curseforge')
            accessToken = providers.gradleProperty('enjaraiCurseforgeToken').get()

            if (min == max) {
                minecraftVersions.add(min)
            } else {
                minecraftVersionRange {
                    start = min
                    end = max
                }
            }

            requires {
                slug = "fabric-api"
            }
            requires {
                slug = "cicada"
            }
            requires {
                slug = "owo-lib"
            }
            requires {
                slug = "lavender-api"
            }
            requires {
                slug = "accessories"
            }
            embeds {
                slug = "cardinal-components-api"
            }
        }
    }

    if (providers.gradleProperty('enjaraiGithubToken').present) {
        github {
            repository = property('mod_github')
            accessToken = providers.gradleProperty('enjaraiGithubToken').get()

            commitish = property('git_branch')
            tagName = project.version
        }
    }
}

tasks.register('publishAll') {
    group 'publishing'
    dependsOn 'publish'
    dependsOn 'publishMods'
}

// the following three lines are so that JDTLS/Eclipse can pick up owo's generated code
((Task)tasks.findByName("sourcesJar")).configure { dependsOn("compileJava") }
sourceSets.main.java.srcDirs += [ 'src/main/generatedJava' ]
compileJava.options.generatedSourceOutputDirectory = file("${projectDir}/src/main/generatedJava/dev/enjarai/trickster/config")
