package mg.dot.feufaro.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.awt.FileDialog
import java.awt.Frame
import java.io.File

@Composable
actual fun rememberFileSaveLauncher(
    onResult: (String?) -> Unit
): FileSaveLauncher {
    return remember {
        object : FileSaveLauncher {
            override fun launch(defaultName: String, initialDir: String?) {
                CoroutineScope(Dispatchers.IO).launch {
                    val dialog = FileDialog(null as Frame?, "Sauvegarder la source", FileDialog.SAVE)
                    dialog.directory = initialDir
                    dialog.file = defaultName
                    dialog.isVisible = true

                    val path = if (dialog.directory != null && dialog.file != null) {
                        File(dialog.directory, dialog.file).absolutePath
                    } else {
                        null
                    }

                    withContext(Dispatchers.Main) {
                        onResult(path)
                    }
                }
            }
        }
    }
}