import java.nio.file.Files
import java.nio.file.Paths

plugins {
    id 'java'
    id 'com.gradleup.shadow' version '9.0.0-beta10'
    id("xyz.jpenilla.run-paper") version "2.3.1"
}

group = project.group
version = project.version

def targetJavaVersion = 21
java {
    def javaVersion = JavaVersion.toVersion(targetJavaVersion)
    sourceCompatibility = javaVersion
    targetCompatibility = javaVersion
    toolchain.languageVersion.set(JavaLanguageVersion.of(21))
    if (JavaVersion.current() < javaVersion) {
        toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
    }
}

repositories {
    mavenCentral()
    maven {
        url "https://repo.dmulloy2.net/repository/public/"
    }
    maven {
        name = 'spigotmc-repo'
        url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
    }
    maven {
        name = "papermc"
        url = uri("https://repo.papermc.io/repository/maven-public/")
    }
    maven {
        name = 'sonatype'
        url = 'https://oss.sonatype.org/content/groups/public/'
    }
    maven {
        name = "CodeMC"
        url = uri("https://repo.codemc.io/repository/maven-public/")
    }
    maven { url 'https://jitpack.io' }
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.11.0")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.11.0")
    compileOnly "io.papermc.paper:paper-api:1.21.5-R0.1-SNAPSHOT"
    implementation 'com.google.code.gson:gson:2.10.1'
    implementation 'org.ow2.asm:asm-commons:9.5'
    implementation files("libs/PDK-1.4.0.jar")
    implementation "com.github.retrooper:packetevents-spigot:2.8.0"
    implementation("de.tr7zw:item-nbt-api:2.15.0")
}

static def generateBuildId() {
    return new Date().format('HH:mm:ss dd/MM/yyyy')
}

processResources {
    filesMatching('plugin.yml') {
        expand(
                version: project.version,
                build: generateBuildId()
        )
    }
}

shadowJar {
    archiveClassifier.set('')
    minimize()
    mergeServiceFiles()

    filesMatching('**/plugin.yml') { fileCopyDetails ->
        def content = fileCopyDetails.file.text
        def lines = content.split('\n')

        if (lines.length == 0 || !lines[0].trim().equals('name: SentinelAntiNuke')) {
            fileCopyDetails.exclude()
        }
    }


    relocate("com.github.retrooper.packetevents", "me.trouper.sentinel.packetevents.api")
    relocate("io.github.retrooper.packetevents", "me.trouper.sentinel.packetevents.impl")
    relocate("de.tr7zw.changeme.nbtapi", "me.trouper.sentinel.nbtapi.api")
}

task copyLibs {
    doLast {
        def sourceDir = Paths.get("${System.getProperty('user.home')}/.gradle/caches/modules-2/files-2.1")
        def targetDir = Paths.get("${buildDir}/../deps")

        if (!Files.exists(targetDir)) {
            Files.createDirectories(targetDir)
        }

        Files.walk(sourceDir)
                .filter { Files.isRegularFile(it) && it.toString().endsWith(".jar") }
                .forEach { jarFile ->
                    def fileName = jarFile.fileName.toString()
                    def targetFile = targetDir.resolve(fileName)

                    if (Files.exists(targetFile)) {
                        println "Skipping duplicate file: ${fileName}"
                        return
                    }

                    Files.copy(jarFile, targetFile)
                    println "Copied: ${jarFile} -> ${targetFile}"
                }

        println "All JAR files have been extracted to: ${targetDir}"
    }
}

task obfuscate(type: JavaExec) {
    classpath = files('obf/grunt-main.jar')
    args = [
            '--config', 'obf/config.json'
    ]
}

tasks.withType(JavaCompile).configureEach {
    options.encoding = "UTF-8"
    if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
        options.release = targetJavaVersion
    }
}

test {
    useJUnitPlatform()
}

build {
    dependsOn(shadowJar)
}

tasks {
    runServer {
        dependsOn(shadowJar)
        minecraftVersion("1.21.5")
    }
}