package mg.dot.feufaro.di

import feufaro.composeapp.generated.resources.Res
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import mg.dot.feufaro.FileRepository
import java.awt.FileDialog
import java.awt.Frame
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream

class DesktopFileRepository : FileRepository { // IMPORTS AND IMPLEMENTS THE commonMain 'FileRepository' interface
    override suspend fun getOutputStream(filePath: String): OutputStream {
        val outputFile = File(filePath)
        return FileOutputStream(outputFile)
    }
    override suspend fun readFileLines(filePath: String): List<String> = withContext(Dispatchers.IO) {
        try {
            when {
                filePath.startsWith("assets://") -> {
                    readAssetFileLines(filePath)
                }

                else -> {
                    File(filePath).readLines()
                }
            }
        } catch (e: IOException) {
            throw IOException("Failed to read file or asset '$filePath'")
        }
    }
    override suspend fun readFileContent(filePath: String): String = withContext(Dispatchers.IO) {
        val lines = readFileLines(filePath)
        lines.joinToString("\n") { it }
    }
    private suspend fun readAssetFileLines(assetFileName: String): List<String> {
        return try {
            Res.readBytes("files/"+assetFileName.removePrefix("assets://")).decodeToString().split("\n")
        } catch (e: IOException) {
            println("Could not read /"+assetFileName.removePrefix("assets://"))
            throw IOException("Could not read asset file: $assetFileName", e)
        }
    }
    override suspend fun saveFile(filePath: String, data: ByteArray) {
        val userHome = System.getProperty("user.home")
        val file = File("$userHome/$filePath")
        file.writeBytes(data) // Extension Kotlin très efficace
    }
    override suspend fun saveLocalFile(filePath: String, data: ByteArray) {
        val file = if (filePath.startsWith("/")) {
            File(filePath)                          // chemin absolu → utilisé directement
        } else {
            File(System.getProperty("user.home"), filePath)  // chemin relatif → préfixé
        }
        file.parentFile?.mkdirs()  // crée les dossiers parents si nécessaire
        file.writeBytes(data) // Extension Kotlin très efficace
    }

    override fun getFileName(shortName: String): String {
        val userHome = System.getProperty("user.home")
        return "$userHome/$shortName"
    }

    override fun pickSavePath(defaultName: String): String? {
        val dialog = FileDialog(null as Frame?, "Exporter en PDF", FileDialog.SAVE)
        dialog.directory = System.getProperty("user.home")
        dialog.file = defaultName
        dialog.isVisible = true

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