/*
 * Copyright 2019-2022 Mamoe Technologies and contributors.
 *
 * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
 * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
 *
 * https://github.com/mamoe/mirai/blob/dev/LICENSE
 */

@file:Suppress("UnusedImport")

plugins {
    kotlin("jvm")
    id("java-gradle-plugin")
}

dependencies {
    implementation(gradleApi())
    implementation(gradleKotlinDsl())
    implementation(`kotlin-reflect`)
    implementation(kotlin("gradle-plugin-api"))
    implementation(kotlin("gradle-plugin"))
    implementation(kotlin("stdlib"))

    api("com.github.jengelman.gradle.plugins:shadow:6.0.0")
    api(`jetbrains-annotations`)

    testImplementation(kotlin("test-junit5"))
    testImplementation(`junit-jupiter-api`)
    testImplementation(`junit-jupiter-params`)
    testRuntimeOnly(`junit-jupiter-engine`)
}

tasks.getByName("test", Test::class) {
    environment("mirai.root.project.dir", rootProject.projectDir.absolutePath)
    systemProperty("mirai.deps.test.must.run", System.getProperty("mirai.deps.test.must.run"))
}

val publishMiraiArtifactsToMavenLocal by tasks.registering {
    group = "mirai"
    description = "Publish all mirai artifacts to MavenLocal"
    val publishTasks = rootProject.allprojects.mapNotNull { proj ->
        proj.tasks.findByName("publishToMavenLocal")
    }
    dependsOn(publishTasks)

    doFirst {
        // Always print this very important message
        logger.warn("[publishMiraiArtifactsToMavenLocal] Project version is '${project.version}'.")
    }

    doLast {
        // delete shadowed Jars, since Kotlin can't compile modules that depend on them.
        rootProject.subprojects
            .asSequence()
            .flatMap { proj -> proj.tasks.filter { task -> task.name.contains("relocate") } }
            .flatMap { it.outputs.files }
            .filter { it.isFile && it.name.endsWith(".jar") }
            .forEach { it.delete() }
    }
}


tasks.register("updateProjectVersionForLocalDepsTest") {
    doLast {
        setProjectVersionForFutureBuilds(DEPS_TEST_VERSION)
    }
}

tasks.register("generateBuildConfig") {
    group = "mirai"

    doLast {
        generateBuildConfig()
    }
    tasks.getByName("testClasses").dependsOn(this)
    tasks.getByName("compileTestKotlin").dependsOn(this)
}

generateBuildConfig() // somehow "generateBuildConfig" won't execute

fun generateBuildConfig() {
    val text = """
            package net.mamoe.mirai.deps.test
            
            /**
             * This file was generated by Gradle task `generateBuildConfig`.
             */
            object BuildConfig {
                /**
                 * Kotlin version used to compile mirai-core
                 */
                const val kotlinVersion = "${Versions.kotlinCompiler}"
            }
        """.trimIndent() + "\n"
    val file = project.projectDir.resolve("test/BuildConfig.kt")
    if (!file.exists() || file.readText() != text) {
        file.writeText(text)
    }
}

/**
 * Kind note: To run this task you probably need a lot of host memory and luck.
 *
 * **If you see errors, don't panic, that's most probably not your fault.**
 *
 * Try:
 *
 * ```shell
 * ./gradlew :mirai-deps-test:updateProjectVersionForLocalDepsTest
 * ./gradlew clean :mirai-deps-test:publishMiraiArtifactsToMavenLocal "-Porg.gradle.parallel=false"
 * ```
 * Note this will change your project version in `buildSrc/src/main/kotlin/Versions.kt`. Be careful to change it back before committing!
 * Note also this is **extremely slow**. If your computer isn't good enough it may take hours.
 */
val publishMiraiLocalArtifacts = tasks.register("publishMiraiLocalArtifacts", Exec::class) {
    group = "mirai"
    description = "Starts a child process to publish v$DEPS_TEST_VERSION artifacts to MavenLocal"

    workingDir(rootProject.projectDir)
    environment("mirai.build.project.version", DEPS_TEST_VERSION)
    commandLine(
        "./gradlew",
        "clean",
        publishMiraiArtifactsToMavenLocal.name,
        "--no-daemon",
        "--stacktrace",
        "--scan",
        "-Pkotlin.compiler.execution.strategy=in-process"
    )

    standardOutput = System.out
    errorOutput = System.err
}


version = Versions.core
