def dateString = getDate()
group 'com.fbdev.helios'


def javaVersion = JavaVersion.VERSION_21;

//version dateString
version dateString + '-SNAPSHOT'
def jarNameHead = rootProject.name + "-" + version

String packageDir = getLayout().getBuildDirectory().dir("packageDir").get()

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    // https://mvnrepository.com/artifact/net.java.jinput/jinput
    implementation group: 'net.java.jinput', name: 'jinput', version: '2.0.10'
    // https://mvnrepository.com/artifact/com.google.guava/guava
    implementation group: 'com.google.guava', name: 'guava', version: '33.5.0-jre'
    implementation group: 'org.jctools', name: 'jctools-core', version: '4.0.4'
    // https://mvnrepository.com/artifact/org.digitalmediaserver/cuelib-core
    implementation group: 'org.digitalmediaserver', name: 'cuelib-core', version: '2.0.0'
    implementation group: 'com.github.trilarion', name: 'java-vorbis-support', version: '1.2.1'
    // https://mvnrepository.com/artifact/org.jaudiolibs/audioservers-javasound
    implementation group: 'org.jaudiolibs', name: 'audioservers-javasound', version: '2.0.0'
    implementation 'com.google.code.gson:gson:2.13.2'
    implementation 'com.formdev:flatlaf:3.6.1'
    implementation group: 'org.ow2.asm', name: 'asm', version: '9.8'
    implementation group: 'org.ow2.asm', name: 'asm-commons', version: '9.8'
    implementation group: 'org.ow2.asm', name: 'asm-util', version: '9.8'

    implementation 'org.tinylog:tinylog-api:2.7.0'
    implementation 'org.tinylog:tinylog-impl:2.7.0'
    implementation 'org.tinylog:slf4j-tinylog:2.7.0'

    testImplementation group: 'junit', name: 'junit', version: '4.13.2'
    // https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api
    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.13.0'
    testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.13.0'

    //include local jars
    implementation fileTree(dir: 'lib', include: ['*.jar'])
    testImplementation fileTree(dir: 'lib', include: ['*.jar'])
}

def static getDate() {
    String date = new Date().format('yyMMdd')
    date.substring(0,2) + "." + date.substring(2)
}

// Java
java.toolchain {
    languageVersion.set(JavaLanguageVersion.of(javaVersion.getMajorVersion()))
    assert JavaVersion.current().isCompatibleWith(javaVersion): "Java " + javaVersion + " or newer is required"
    println("Java version: " + JavaVersion.current())
}

//create a single Jar with all dependencies
tasks.register('fatJar', Jar) {
    manifest {
        attributes 'Implementation-Title': 'Helios',
                'Implementation-Version': archiveVersion,
                'Main-Class': 'omegadrive.SystemLoader'
    }
    getArchiveBaseName().set(project.name + "-all")//+ version
    from { configurations.implementation.collect { it.isDirectory() ? it : zipTree(it) } }
    from {
        ["CREDITS.md", "README.md", "HISTORY.md", "LICENSE.md", "helios.properties"]
    }
    from("bios") {
        include "*.rom"
    }
    with jar
    doLast {
        println("Creating fatJar in folder: " + destinationDirectory)
    }
}

tasks.register('copyRes') {
    copy {
        from(".") {
            include "res/**"
        }
        into packageDir
        exclude "**/*.col", "**/bios.sms", "**/site/**", "**/misc/**", "**/sms/**", "**/mcd/**", "**/32x_bios_?.bin"
    }
    copy {
        from {
            ["CREDITS.md", "README.md", "HISTORY.md",
             "LICENSE.md", "helios.properties", "key.config.1p"]
        }
        into packageDir
    }
    copy {
        from(".") {
            include "lib/**"
        }
        into packageDir
    }
    copy {
        from configurations.runtimeClasspath
        into packageDir + "/lib"
    }
}

jar {
    manifest {
        attributes 'Implementation-Title': 'Helios',
                   'Implementation-Version': archiveVersion,
                   'Main-Class': 'omegadrive.SystemLoader',
                   'Class-Path': configurations.compileClasspath.collect { "lib/" + it.getName() }.join(' ')
    }
    getArchiveBaseName().set(rootProject.name)
    destinationDirectory = file(packageDir)
    doLast {
        println("Creating jar: " + getArchiveFileName().getOrNull() +
                " in folder: " + getDestinationDirectory().getOrNull())
    }
}

tasks.register('jarWithSources', org.gradle.jvm.tasks.Jar) {
    from sourceSets.main.allSource
    manifest {
        attributes 'Implementation-Title': 'Helios',
                'Implementation-Version': archiveVersion,
                'Main-Class': 'omegadrive.SystemLoader',
                'Class-Path': configurations.compileClasspath.collect { "lib/" + it.getName() }.join(' ')
    }
    getArchiveFileName().set(rootProject.name + "-binsrc-${project.version}.jar")
    destinationDirectory = file(packageDir)
    with jar
    doLast {
        println("Creating jar with sources: " + getArchiveFileName().getOrNull() +
                " in folder: " + getDestinationDirectory().getOrNull())
    }
}

tasks.register('packageDistribution', Zip) {
    dependsOn "test", "jar", "copyRes", "writeToFile"
    archiveFileName = jarNameHead + ".zip"
    destinationDirectory = file(getLayout().getBuildDirectory().dir("dist"))

    from packageDir
    doLast {
        println("Creating package: " + getArchiveFileName().getOrNull() +
                ", folder: " + getDestinationDirectory().getOrNull())
        println("" + getDestinationDirectory().getOrNull() + "/" + getArchiveFileName().getOrNull())
    }
}

tasks.register('writeToFile') {
    String jarName = jarNameHead + ".jar"
    List<String> javaAdvOpts =
            ["-XX:AutoBoxCacheMax=65536", "-XX:-DontCompileHugeMethods", "-XX:+AlwaysCompileLoopMethods"]
    //win: default to busy wait
    List<String> winOpts = ["-Dhelios.busy.wait=true"]
    List<String> sampleBase = ["java",
                               "-Dtinylog.configuration=./res/tinylog.properties",
                               "-Djinput.enable=true -Djinput.native.location=lib",
                               "-jar", "$jarName"] as String[]
    sampleBase.addAll(1, javaAdvOpts)
    List<String> sampleUx = new ArrayList<>(sampleBase)
    sampleUx.add("\"\$@\"" + "\n")
    List<String> sampleWin = new ArrayList<>(sampleBase)
    sampleWin.addAll(1, winOpts)
    sampleWin.add("\"%1\"" + "\n")
    // create the folders if it does not exist.(otherwise it will throw exception)
    File extraFolder = new File(packageDir)
    if (!extraFolder.exists()) {
        extraFolder.mkdirs()
    }
    // create the file and write text to it.
    Directory dir = getLayout().getBuildDirectory().dir("packageDir").get()
    dir.file("launcher.sh").getAsFile().text = sampleUx.join(" ")
    dir.file("launcher.bat").getAsFile().text = sampleWin.join(" ")
}

test {
    testLogging {
        afterSuite { desc, result ->
            if (!desc.parent) { // will match the outermost suite
                println "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)"
            }
        }
    }
}
