import java.nio.file.Files

plugins {
    id "java"
}

java.toolchain.languageVersion = JavaLanguageVersion.of(21)

tasks.processResources {
    filesMatching('plugin.json') {
        expand(
                version: project.version,
                pluginVersion: project.pluginVersion
        )
    }
}

tasks.jar {
    archiveFileName.set(Globals.getArchiveName())
}

class Globals {
    private static final def ARCHIVE_NAME = "generator-fabric-1.21.8" // The name of the exported file

    // You can change the root folder of your OS if you have a custom installation
    public static final def MCREATOR_ROOT_FOLDER_WINDOWS = "C:\\Program Files\\Pylo\\MCreatorEAP2025338713" // Default path on Windows
    public static def MCREATOR_ROOT_FOLDER_MAC_LINUX = "/Applications/MCreator.app/Contents/MacOS/mcreator" // Default path on macOS and Linux

    static def getArchiveName() {
        return ARCHIVE_NAME + ".zip"
    }

    static String getOSName() {
        return System.getProperty("os.name").toLowerCase()
    }

    static String getUserHome() {
        return System.getProperty("user.home") //user.name is the name of the pc, not the name of the directory
    }
}

// workaround for IDEA-265203
System.setProperty("user.dir", projectDir.toString())

tasks.register('copyLibs', Copy) {
    dependsOn(jar)

    from("build/libs")
    into("build")
}

tasks.register('exportPlugin', Zip) {
    dependsOn(processResources, jar, tasks.named('copyLibs'))

    group("mcreator_plugins")
}

tasks.register('install') {
    dependsOn exportPlugin
    group("mcreator_plugins")
    doLast {
        println("Installing plugin...")
        if (Globals.getOSName().contains('mac') || Globals.getOSName().contains('OS X') || Globals.getOSName().contains('linux')) {
            installPlugin("${Globals.getUserHome()}/.mcreator/plugins/", "/")
        } else if (Globals.getOSName().contains('windows')) {
            installPlugin("${Globals.getUserHome()}\\.mcreator\\plugins\\", "\\")
        }
    }
}

tasks.register('runMCreator') {
    dependsOn install
    group("mcreator_plugins")
    doLast {
        println("Launching MCreator...")
        if (Globals.getOSName().contains('windows')) {
            try {
                tasks.named('runMCreatorFromCMD').get().exec()
            } catch (IOException e) {
                //noinspection GroovyAssignabilityCheck
                throw new RuntimeException("Could not launch MCreator! Please make sure you have installed it to " + Globals.MCREATOR_ROOT_FOLDER_WINDOWS, e)
            }
        } else if (Globals.getOSName().contains('mac') || Globals.getOSName().contains('OS X') || Globals.getOSName().contains('linux')) {
            try {
                ProcessBuilder builder = new ProcessBuilder(Globals.MCREATOR_ROOT_FOLDER_MAC_LINUX)
                builder.redirectOutput(ProcessBuilder.Redirect.INHERIT)
                builder.redirectError(ProcessBuilder.Redirect.INHERIT)
                builder.start()
            } catch (IOException e) {
                //noinspection GroovyAssignabilityCheck
                throw new RuntimeException("Could not launch MCreator! Please make sure you have installed it to " + Globals.MCREATOR_ROOT_FOLDER_MAC_LINUX, e)
            }
        }
    }
}

//For Gradle 9
tasks.register('runMCreatorFromCMD', Exec) {
    workingDir Globals.MCREATOR_ROOT_FOLDER_WINDOWS
    commandLine 'cmd', '/c', 'mcreator.exe'
    standardOutput = System.out
    errorOutput = System.err
    ignoreExitValue = false
}

static def installPlugin(String path, String separator) {
    File des = new File(path + Globals.getArchiveName())
    File original = new File("${System.getProperty("user.dir")}${separator}build${separator}${Globals.getArchiveName()}")
    if (des.exists()) {
        des.delete()
    }
    try {
        FileOutputStream os = new FileOutputStream(des)
        Files.copy(original.toPath(), os)
        println("Plugin successfully installed to $path")
    } catch (IOException e) {
        e.printStackTrace()
        throw new RuntimeException("Could not install plugin!")
    }
}

subprojects { subproject ->
    subproject.plugins.withType(JavaPlugin) {
        test {
            useJUnitPlatform()
            include '**/GeneratorsTest.class'

            dependsOn rootProject.processResources
            dependsOn rootProject.jar

            environment("MCREATOR_PLUGINS_FOLDER", new File(rootProject.projectDir, "/build/libs"))
            environment("MCREATOR_PLUGINS_DEV", "")
            environment("MCREATOR_TEST_GENERATORS", "fabric-${version}")

            workingDir = mcreator_path
        }
    }
}