package deckers.thibault.aves

import android.content.ContentUris
import android.content.Context
import android.provider.MediaStore
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class EntryPathChannel(private val context: Context) {

    fun register(flutterEngine: FlutterEngine) {
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            "aves/entry_path"
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                "getEntryPath" -> {
                    // Accetta sia int che string
                    val rawId: Any? = call.argument<Any>("id")
                    val id = when (rawId) {
                        is Number -> rawId.toLong()
                        is String -> rawId.toLongOrNull()
                        else -> null
                    }

                    if (id == null) {
                        result.error("INVALID_ID", "ID non valido: $rawId", null)
                        return@setMethodCallHandler
                    }

                    val path = getPathForMediaStoreId(id)
                    if (path != null) {
                        result.success(path)
                    } else {
                        result.error("NOT_FOUND", "Nessun file per ID=$id", null)
                    }
                }

                else -> result.notImplemented()
            }
        }
    }

    private fun getPathForMediaStoreId(id: Long): String? {
        val uri = ContentUris.withAppendedId(
            MediaStore.Files.getContentUri("external"),
            id
        )

        val projection = arrayOf(MediaStore.Files.FileColumns.DATA)

        context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)
                if (idx >= 0) {
                    return cursor.getString(idx)
                }
            }
        }

        return null
    }
}
