plugins {
    alias(libs.plugins.kotlin.multiplatform)
    alias(libs.plugins.compose.compiler)
    alias(libs.plugins.compose.multiplatform)
    alias(libs.plugins.android.kmp.library)
    alias(libs.plugins.undercouch.download)
}

repositories {
    google()
    mavenCentral()
    maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}

kotlin {
    jvm()

    androidLibrary {
        namespace = "theorycrafter.evedata"
        compileSdk = libs.versions.android.compileSdk.get().toInt()
        minSdk = libs.versions.android.minSdk.get().toInt()
    }

    sourceSets {
        commonMain.dependencies {
            api(compose.runtime)
        }
    }

    compilerOptions.freeCompilerArgs.apply {
        add("-Xlambdas=indy")
        add("-Xcontext-receivers")
    }
}

// Converts the SDE into an eve_data.dat file the app can read.
open class ImportEveDataTask : DefaultTask() {

    @InputFile
    lateinit var input: File

    @InputDirectory
    lateinit var eveCacheDir: File

    @InputFile
    lateinit var output: File

    @InputDirectory
    lateinit var iconsOutputDir: File

    @TaskAction
    fun importData() {
        importSde(
            sdeFile = input,
            eveCacheDir = eveCacheDir,
            outputFile = output,
            iconsOutputDir = iconsOutputDir
        )
    }

}

// Generate the eve data file from the SDE:
// https://wiki.eveuniversity.org/Static_Data_Export
// https://developers.eveonline.com/resource/resources
val sdeFile = File(projectDir, "../misc/sde.zip").normalize()

// Generate the eve data
val generateEveData = tasks.register<ImportEveDataTask>("generateEveData") {
    group = "eve"
    input = sdeFile
    eveCacheDir = File(System.getProperty("user.home"), "Library/Application Support/EVE Online/SharedCache").normalize()
    output = project.file("src/commonMain/resources/eve_data.dat")
    iconsOutputDir = project.file("src/commonMain/resources/icons")

    mustRunAfter(downloadSdeFile)
}


// Download the SDE file
// The latest URL is available at https://developers.eveonline.com/static-data
// Also see https://developers.eveonline.com/docs/services/static-data/#automation
val sdeUrl = "https://developers.eveonline.com/static-data/tranquility/eve-online-static-data-3187404-yaml.zip"
val downloadSdeFile = tasks.register<de.undercouch.gradle.tasks.download.Download>("downloadSdeFile") {
    src(sdeUrl)
    dest(sdeFile)
    connectTimeout(10_000)
    readTimeout(10_000)
}

// Re-download the SDE file and re-generate the eve data
tasks.register("updateEveData") {
    group = "eve"
    dependsOn(downloadSdeFile, generateEveData)
}
