import org.jetbrains.compose.desktop.application.dsl.TargetFormat
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import java.util.Properties

plugins {
    alias(libs.plugins.kotlinMultiplatform)
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.composeMultiplatform)
    alias(libs.plugins.composeCompiler)
    //alias(libs.plugins.composeHotReload)
    alias(libs.plugins.kotlinSerialization)
}

kotlin {
    /*linuxX64 {
        binaries {
            executable {

            }
        }
    }*/
    androidTarget {
        @OptIn(ExperimentalKotlinGradlePluginApi::class)
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_11)
        }
    }
    
    jvm("desktop")

    afterEvaluate {
        afterEvaluate {
            tasks.configureEach {
                if (
                    name.startsWith("compile")
                    && name.endsWith("KotlinMetadata")
                ) {
                    println("disabling $name")
                    enabled = false
                }
            }
        }
    }
    sourceSets {
        val desktopMain by getting
        
        androidMain.dependencies {
            implementation(compose.preview)
            implementation(libs.androidx.activity.compose)
            implementation(libs.koin.android) // Koin Android-specific extensions
            implementation(libs.koin.androidx.compose)
            implementation("com.google.zxing:core:3.5.4")
            implementation("com.github.billthefarmer:mididriver:1.25")
            implementation("com.tom-roush:pdfbox-android:2.0.27.0")
        }
        commonMain.dependencies {
//            implementation(compose.components.resources)
            implementation(compose.runtime)
            implementation(compose.foundation)
            implementation(compose.material3)
            implementation(compose.ui)
            implementation(compose.components.resources)
            implementation(compose.components.uiToolingPreview)
            implementation(libs.androidx.lifecycle.viewmodel)
            implementation(libs.androidx.lifecycle.runtimeCompose)
            implementation(libs.koin.core) // Koin core for shared logic
            implementation(libs.koin.compose) // Koin for Compose Multiplatform UI
            implementation(libs.koin.compose.viewmodel) // Koin for KMP ViewModels

            implementation(libs.kotlinx.serialization.json)
            implementation(libs.bundles.voyager)
            implementation(libs.cafe.voyager.koin)
            implementation(compose.materialIconsExtended)
            //implementation(kotlin("stdlib-jdk8"))
            //implementation("org.jetbrains.compose.foundation:foundation-desktop")
            implementation("com.russhwolf:multiplatform-settings-no-arg:1.3.0")
            implementation("io.github.pdvrieze.xmlutil:serialization:0.91.3") // Dépendance sous-jacente pour XML
            //implementation(libs.ktmidi)
        }
        commonTest.dependencies {
            implementation(libs.kotlin.test)
        }
        desktopMain.dependencies {
            implementation(compose.desktop.currentOs)
            implementation(libs.kotlinx.coroutinesSwing)
            implementation("com.google.zxing:core:3.5.4")
            implementation("com.google.zxing:javase:3.5.4")
            implementation("org.apache.pdfbox:pdfbox:3.0.7")
        }
    }
    targets.all {
        compilations.all {
            compileTaskProvider.configure {
                compilerOptions {
                    freeCompilerArgs.add("-Xexpect-actual-classes")
                }
            }
        }
    }
}

android {
    namespace = "mg.dot.feufaro"
    compileSdk = libs.versions.android.compileSdk.get().toInt()

    defaultConfig {
        applicationId = "mg.dot.feufaro"
        minSdk = libs.versions.android.minSdk.get().toInt()
        targetSdk = libs.versions.android.targetSdk.get().toInt()
        versionCode = 1
        versionName = "1.0"
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
}

dependencies {
    debugImplementation(compose.uiTooling)
}

compose.desktop {
    application {
        mainClass = "mg.dot.feufaro.MainKt"

        nativeDistributions {
            targetFormats(TargetFormat.Exe, TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
            packageName = "Feufaro"
            packageVersion = "1.0.0"
            modules("java.base", "java.desktop", "jdk.unsupported", "java.naming")

            buildTypes.release.proguard {
                isEnabled.set(false)
            }
        }
    }
}
val generateFilesIndex = tasks.register("generateFilesIndex") {
    val resourcesDir = file("src/commonMain/composeResources/files")
    val outputFile = file("src/commonMain/composeResources/files/feuList.txt")

    inputs.dir(resourcesDir)
    outputs.file(outputFile)

    doLast {
        if (resourcesDir.exists()) {
            val lines = resourcesDir.listFiles()
                ?.filter { it.extension == "txt" && it.name != "feuList.txt" }
                ?.sortedBy { it.name }
                ?.map { file ->
                    var title = "Sans titre"
                    file.useLines { lines ->
                        for (l in lines) {
                            if (l.contains("|t:")) {
                                title = l.substringAfter("|t:").substringBefore("|").trim()
                                break
                            }
                        }
                    }
                    "${file.name}|$title"
                } ?: emptyList()
            outputFile.writeText(lines.joinToString("\n"))
            println("Génération de l'index : ${lines.size} fichiers indexés.")
        }
    }
}
tasks.configureEach {
    if (name.startsWith("copyNonXmlValueResources") ||
        name.startsWith("generateComposeResClass")) {
        dependsOn(generateFilesIndex)
    }
}