package mg.dot.feufaro

import android.Manifest
import android.app.ComponentCaller
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Base64
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import org.koin.androidx.compose.KoinAndroidContext
import java.io.File
import java.util.zip.GZIPInputStream

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
            1
        )
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        setFilePickerActivity(this)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        hideSystemBar()
        intent?.let { handleDeepLinkIntent(it) }


        setContent {
            KoinAndroidContext {
                App()
            }
        }
    }
    @Suppress("OVERRIDE_DEPRECATION")
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleDeepLinkIntent(intent)
    }
    override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
        super.onNewIntent(intent, caller)
        setIntent(intent)
        handleDeepLinkIntent(intent)
    }

    private fun decodeAndDecompress(base64Data: String): String {
        return try {
            val compressedBytes = Base64.decode(base64Data, Base64.URL_SAFE)
            java.util.zip.GZIPInputStream(compressedBytes.inputStream()).bufferedReader(Charsets.UTF_8).use {
                it.readText()
            }
        } catch (e: Exception) {
            println("Decompression Error: ${e.message}")
            base64Data
        }
    }
    private fun handleDeepLinkIntent(intent: Intent) {
        println("DeepLink: intent reçu = ${intent.data}")

        val data: Uri = intent.data ?: run {
            println("DeepLink: data est null")
            return
        }

        println("DeepLink: scheme=${data.scheme} host=${data.host}")

        if (data.scheme != "feufaro" || data.host != "song") {
            println("DeepLink: scheme/host incorrect")
            return
        }

        val encodedData = data.getQueryParameter("file") ?: run {
            println("DeepLink: paramètre 'file' introuvable")
            return
        }
        val rawContent = decodeAndDecompress(encodedData)

        println("DeepLink: rawContent = $rawContent")

        val fileName = rawContent
            .split("|")
            .firstOrNull { it.startsWith("t:") }
            ?.removePrefix("t:")
            ?.trim()

        println("DeepLink: fileName extrait = $fileName")

        if (fileName.isNullOrBlank()) {
            println("DeepLink: fileName vide ou null")
            return
        }

        val docsDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOCUMENTS
        )
        println("DeepLink: docsDir = ${docsDir.absolutePath}, exists=${docsDir.exists()}")

        val appDir = File(docsDir, "Feufaro")
        appDir.mkdirs()
//        docsDir.mkdirs()

        val file = File(appDir, "$fileName.txt")

        try {
            file.writeText(rawContent)
            println("DeepLink: fichier créé → ${file.absolutePath}")
            DeepLinkHandler.hasConsumedDeepLink = true
            DeepLinkHandler.handleSongContent(rawContent, file.absolutePath)
        } catch (e: Exception) {
            println("DeepLink: ERREUR écriture fichier → ${e.message}")
        }
    }

    private fun extractFileName(content: String): String? {
        return content
            .split("|")
            .firstOrNull { it.startsWith("H:") }
            ?.removePrefix("H:")
            ?.trim()
    }
    private fun hideSystemBar() {
        // Pour les versions d'Android plus récentes (API 30+)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)

            // Cacher les barres système
            windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())

            // Définir le comportement des barres système pour le mode immersif
            // BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE: Les barres apparaissent temporairement
            // après un balayage et disparaissent ensuite. C'est le comportement le plus courant
            // pour le mode immersif.
            windowInsetsController.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        } else {
            // Pour les versions d'Android plus anciennes (API < 30)
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // Rend le mode immersif "collant"
                            or android.view.View.SYSTEM_UI_FLAG_FULLSCREEN // Cache la barre d'état
                            or android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // Cache la barre de navigation
                            or android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    )
            // Utiliser FLAG_LAYOUT_NO_LIMITS pour s'assurer que le contenu s'étend derrière la barre de navigation si elle réapparaît temporairement
            @Suppress("DEPRECATION")
            window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        }
    }
}

@Preview
@Composable
fun AppAndroidPreview() {
    App()
}