package ru.forbion.f7cloud.feature.f7support

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.OpenableColumns
import android.widget.Toast
import androidx.core.content.FileProvider
import java.io.File
import java.util.UUID

data class SupportPendingFile(
    val localId: String = UUID.randomUUID().toString(),
    val fileName: String,
    val bytes: ByteArray,
    val mimeType: String,
)

internal object SupportFileIO {
    fun readUris(context: Context, uris: List<Uri>): List<SupportPendingFile> {
        return uris.mapNotNull { uri ->
            runCatching { readUri(context, uri) }.getOrNull()
        }
    }

    fun readUri(
        context: Context,
        uri: Uri,
        fallbackName: String = "file.bin",
    ): SupportPendingFile {
        val resolver = context.contentResolver
        var name = fallbackName
        resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (idx >= 0) {
                    name = cursor.getString(idx)?.takeIf { it.isNotBlank() } ?: name
                }
            }
        }
        val mime = resolver.getType(uri) ?: "application/octet-stream"
        val bytes = resolver.openInputStream(uri)?.use { it.readBytes() }
            ?: error("Не удалось прочитать файл")
        return SupportPendingFile(fileName = name, bytes = bytes, mimeType = mime)
    }

    fun openBytes(context: Context, fileName: String, bytes: ByteArray, mimeType: String) {
        val safeName = fileName.replace(Regex("[\\\\/:*?\"<>|]"), "_").ifBlank { "file" }
        val cacheDir = File(context.cacheDir, "f7support").apply { mkdirs() }
        val file = File(cacheDir, safeName)
        file.writeBytes(bytes)
        val uri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            file,
        )
        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, mimeType.ifBlank { "application/octet-stream" })
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        try {
            context.startActivity(Intent.createChooser(intent, "Открыть с помощью"))
        } catch (_: ActivityNotFoundException) {
            Toast.makeText(context, "Нет приложения для открытия этого файла", Toast.LENGTH_LONG).show()
        }
    }
}
