package mg.dot.feufaro


import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import java.io.File

private var currentActivity: ComponentActivity? = null
private var fileSelectionCallback: ((String?) -> Unit)? = null
private var filePickerLauncher: ActivityResultLauncher<Intent>? = null


actual fun launchFilePicker(
    mimeTypes: Array<String>,
    initialDirectory: String?,
    onFileSelected: (path: String?) -> Unit
) {
    val launcher = filePickerLauncher
    if (launcher == null) {
        onFileSelected(null)
        // L'Activity n'a pas été initialisée (setFilePickerActivity non appelé).
        return
    }

    // 1. Sauvegarde du callback
    fileSelectionCallback = onFileSelected

    // 2. Crée l'Intent
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = if (mimeTypes.size == 1) mimeTypes[0] else "*/*"
        if (mimeTypes.size > 1) {
            putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
        }
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
    }

    // 3. Lance le sélecteur
    launcher.launch(intent)
}

fun setFilePickerActivity(activity: ComponentActivity) {
    currentActivity = activity

    filePickerLauncher = activity.registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val uri: Uri? = result.data?.data
            if (uri != null) {
                try {
                    activity.contentResolver.takePersistableUriPermission(
                        uri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION
                    )
                } catch (e: Exception) {
                    println("takePersistableUriPermission failed: ${e.message}")
                }
            }
            fileSelectionCallback?.invoke(uri?.toString())
        } else {
            fileSelectionCallback?.invoke(null)
        }
        // Nettoyage
        fileSelectionCallback = null
    }
}