import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

buildscript {
    repositories {
        maven { url "https://nexus.gluonhq.com/nexus/content/repositories/releases" }
        maven { url "https://plugins.gradle.org/m2/" }
        maven { url "https://sandec.jfrog.io/artifactory/repo" }
    }
    dependencies {
        classpath "com.github.jengelman.gradle.plugins:shadow:5.2.0"
        classpath "io.franzbecker:gradle-lombok:4.0.0"
        classpath 'org.openjfx:javafx-plugin:0.0.13'
        classpath 'com.gluonhq:gluonfx-gradle-plugin:1.0.14'
        classpath 'com.sandec.jpro:jpro-plugin-gradle:2022.1.8'
    }
}

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'

apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'io.franzbecker.gradle-lombok'
apply plugin: 'org.openjfx.javafxplugin'
apply plugin: 'com.gluonhq.gluonfx-gradle-plugin'
apply plugin: 'com.sandec.jpro'

repositories {
    mavenCentral()
    //noinspection JCenterRepository
    jcenter()
    maven { url 'https://jitpack.io' }
    maven { url 'https://nexus.gluonhq.com/nexus/content/repositories/releases/' }
}

applicationName = 'Atsumeru Manager'
mainClassName = 'xyz.atsumeru.manager.Application'
version = '1.1'

def appCodeName = "atsumgr"
def versionCode = 2
def updatesCheckUrl = "https://atsumerudev.github.io/AtsumeruManager/update.json"

compileJava.options.encoding = 'UTF-8'
System.setProperty('file.encoding', 'UTF-8')

jpro {
    JVMArgs << '-Xmx1000m'
    port = 8090
}

OperatingSystem os = DefaultNativePlatform.currentOperatingSystem
gluonfx {
    if (os.isWindows()) {
        graalvmHome = WINDOWS_GRAALVM_SDK_PATH
    } else if (os.isLinux()) {
        graalvmHome = LINUX_GRAALVM_SDK_PATH
    } else if (os.isMacOsX()) {
        graalvmHome = MACOSX_GRAALVM_SDK_PATH
    }

    appIdentifier = applicationName
}

nativeBuild {
    applicationDefaultJvmArgs = [
            "-Djava.home=" + gluonfx.graalvmHome,
            "-Djava.awt.headless=true",
            "-Dfile.encoding=UTF-8",
            "-H:+AllowIncompleteClasspath",
            "-H:-IncludeMethodsData",
            "--no-fallback",
            "--enable-http",
            "--enable-https",
            "--allow-incomplete-classpath",
            "--static"
    ]
}

javafx {
    version = '20'
    modules = [ 'javafx.base', 'javafx.controls', 'javafx.fxml', 'javafx.graphics', 'javafx.swing' ]
}

processResources {
    filesMatching('config.properties') {
        def osType = DefaultNativePlatform.currentOperatingSystem.toFamilyName()
        expand([ostype: osType])
    }
}

jar {
    manifest {
        attributes 'Implementation-Title': applicationName,
                'Implementation-Version': version,
                'Main-Class': mainClassName,
                'Built-By': 'AtsumeruDev'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // AnnotationsProcessors
    annotationProcessor 'org.projectlombok:lombok:1.18.22'
    compileOnly 'org.jetbrains:annotations:20.1.0'

    // SubstrateVM features
    compileOnly 'org.graalvm.nativeimage:svm:23.1.0'

    // Kotlin runtime
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10'
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.3.2"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"

    // AtsumeruAPI
    implementation 'com.github.AtsumeruDev:Atsumeru-API:1a8a730'

    // JavaFX
    implementation 'com.jfoenix:jfoenix:9.0.10'
    implementation 'org.controlsfx:controlsfx:9.0.0'
    implementation 'io.github.palexdev:materialfx:11.13.5'
    implementation 'io.github.palexdev:virtualizedfx:11.9.6'
    implementation 'de.jensd:fontawesomefx-commons:11.0'
    implementation 'de.jensd:fontawesomefx-fontawesome:4.7.0-11'
    implementation 'de.jensd:fontawesomefx-materialdesignfont:1.7.22-11'
    implementation 'de.jensd:fontawesomefx-materialicons:2.2.0-11'
    implementation 'org.fxmisc.richtext:richtextfx:0.10.6'
    implementation 'com.github.CrazyXacker:PaletteFX:422d17978d'

    // RxJava
    implementation "io.reactivex:rxjava:1.3.8"
    implementation "io.reactivex.rxjava2:rxjava:2.2.19"

    // Caching
    implementation "com.github.ben-manes.caffeine:caffeine:2.9.0"

    // JSoup
    implementation 'org.jsoup:jsoup:1.15.3'

    // JSON
    implementation 'com.google.code.gson:gson:2.8.9'
    implementation "org.json:json:20160212"
    implementation "org.apache.clerezza.ext:org.json.simple:0.4"

    // OkHttp3 and Retrofit2
    implementation "com.squareup.okhttp3:okhttp:3.12.3"
    implementation "com.squareup.okhttp3:logging-interceptor:3.12.3"
    implementation "com.squareup.okhttp3:okhttp-urlconnection:3.12.3"
    implementation "com.squareup.retrofit2:retrofit:2.4.0"
    implementation "com.squareup.retrofit2:converter-gson:2.4.0"
    implementation "com.squareup.retrofit2:adapter-guava:2.4.0"
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0"
    implementation "com.squareup.retrofit2:converter-scalars:2.4.0"

    // Content detection and Various Archives Support
    implementation "org.apache.tika:tika-core:1.24.1"
    implementation "net.sf.sevenzipjbinding:sevenzipjbinding:16.02-2.01"
    implementation "net.sf.sevenzipjbinding:sevenzipjbinding-all-platforms:16.02-2.01"

    // ImageIO
    implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.8.2'
    implementation 'com.twelvemonkeys.imageio:imageio-webp:3.8.2'

    // Thumbnails Generator/PNG Optimizer
    implementation 'net.coobird:thumbnailator:0.4.11'

    // Natural Comparator
    implementation "net.grey-panther:natural-comparator:1.1"

    // Apache Commons
    implementation "commons-io:commons-io:2.5"
    implementation "org.apache.commons:commons-compress:1.20"

    // SLF4J Logging
    implementation "org.slf4j:slf4j-api:1.7.25"
    implementation "org.slf4j:slf4j-simple:1.7.25"
}

tasks.register('generateJava') {
    ext.outputDir = "$buildDir/generated/java"
    inputs.property('version', project.version)
    outputs.dir outputDir

    def currentOs
    if (os.isLinux()) {
        currentOs = "LINUX"
    } else if (os.isMacOsX()) {
        currentOs = "MACOS"
    } else {
        currentOs = "WINDOWS"
    }

    doFirst {
        mkdir "$outputDir/xyz/atsumeru/manager"
        file("$outputDir/xyz/atsumeru/manager/BuildProps.java").text =
                """|package xyz.atsumeru.manager;
                |import xyz.atsumeru.manager.helpers.JavaHelper;
                |import static xyz.atsumeru.manager.helpers.JavaHelper.SystemType.*;
                |public class BuildProps {
                |    public static String getAppName() { return "${applicationName}"; }
                |    public static String getAppCodeName() { return "${appCodeName}"; }
                |    public static String getVersion() { return "${project.version}"; }
                |    public static int getVersionCode() { return ${versionCode}; }
                |    public static String getUpdatesCheckUrl() { return "${updatesCheckUrl}"; }
                |    public static JavaHelper.SystemType getSystemType() { return ${currentOs}; }
                |    public static String getAppIconName() { return "atsumeru_128"; }
                |}""".stripMargin()
    }

    println "Current OS: ${currentOs}"
}

run.dependsOn generateJava
sourceSets.main.java.srcDir generateJava.outputDir

tasks.register('nativePostBuild') {
    doLast {
        exec {
            def platform
            def binaryName = "AtsumeruManager"
            def binaryExtension = ""
            def upxScriptExtension

            if (os.isLinux()) {
                platform = "linux"
                upxScriptExtension = ".sh"
            } else if (os.isMacOsX()) {
                platform = "darwin"
                upxScriptExtension = ".sh"
            } else {
                platform = "windows"
                binaryExtension = ".exe"
                upxScriptExtension = ".cmd"
            }

            delete "${projectDir}/build/gluonfx/x86_64-" + platform + "/" + binaryName + binaryExtension
            if (!os.isMacOsX()) {
                workingDir "${projectDir}/tools"
                executable "${workingDir}/upx_pack_atsumeru" + upxScriptExtension
            }
        }
    }
}
nativeBuild.dependsOn nativePostBuild

run {
    new File(project.buildDir, "/resources/main/config.properties").delete()
    List<String> args = new ArrayList<String>() {{
        add("--add-opens=javafx.graphics/javafx.css=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.javafx.css=ALL-UNNAMED");
        add("--add-opens=javafx.controls/javafx.scene.control=ALL-UNNAMED");
        add("--add-opens=javafx.controls/javafx.scene.control.skin=ALL-UNNAMED");
        add("--add-opens=java.base/java.lang.reflect=ALL-UNNAMED");
        add("--add-opens=java.base/sun.nio.ch=ALL-UNNAMED");
        add("--add-opens=java.base/java.io=ALL-UNNAMED");
        add("--add-opens=javafx.controls/javafx.scene.control.skin=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/javafx.scene=ALL-UNNAMED");
        add("--add-opens=javafx.base/com.sun.javafx.runtime=ALL-UNNAMED");
        add("--add-opens=javafx.base/com.sun.javafx.collections=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.javafx.css=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.javafx.scene.traversal=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/javafx.scene=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.glass.ui=ALL-UNNAMED");
        add("--add-opens=javafx.graphics/com.sun.javafx.util=ALL-UNNAMED");
        add("--add-opens=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED");
        add("--add-opens=javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED");
        add("--add-opens=javafx.controls/javafx.scene.control.skin=ALL-UNNAMED");

        add("--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED");
        add("--add-exports=javafx.controls/javafx.scene.control=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control.inputmap=ALL-UNNAMED");
        add("--add-exports=javafx.graphics/com.sun.javafx.scene.traversal=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED");
        add("--add-exports=javafx.base/com.sun.javafx.binding=ALL-UNNAMED");
        add("--add-exports=javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED");
        add("--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED");
        add("--add-exports=javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED");
        add("--add-exports=javafx.graphics/com.sun.javafx.scene.traversal=ALL-UNNAMED");
        add("--add-exports=javafx.graphics/com.sun.javafx.util=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED");
        add("--add-exports=javafx.controls/com.sun.javafx.scene.control.inputmap=ALL-UNNAMED");
        add("--add-exports=javafx.base/com.sun.javafx.event=ALL-UNNAMED");
        add("--add-exports=javafx.base/com.sun.javafx.collections=ALL-UNNAMED");
        add("--add-exports=javafx.base/com.sun.javafx.runtime=ALL-UNNAMED");
    }}

    applicationDefaultJvmArgs = args
    jvmArgs = args
}