package com.ariacockpit

import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.io.File

/**
 * Oeffnet eine beliebige Datei (PDF, Bild, Office-Doc, ...) mit der vom User
 * gewaehlten App via Android-Intent-Picker. Nutzt FileProvider damit auch
 * Android 7+ (content:// statt file://) das URI lesen darf.
 *
 * MIME-Type wird vom Caller bestimmt — App-Auswahl ist davon abhaengig (PDF
 * geht an PDF-Viewer, image/jpeg an Galerie, etc.).
 */
class FileOpenerModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
    override fun getName() = "FileOpener"

    @ReactMethod
    fun open(filePath: String, mimeType: String, promise: Promise) {
        try {
            val cleanPath = filePath.removePrefix("file://")
            val file = File(cleanPath)
            if (!file.exists()) {
                promise.reject("FILE_NOT_FOUND", "Datei nicht gefunden: $cleanPath")
                return
            }
            val context = reactApplicationContext
            val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
            } else {
                Uri.fromFile(file)
            }
            val safeMime = if (mimeType.isBlank()) "application/octet-stream" else mimeType
            val intent = Intent(Intent.ACTION_VIEW).apply {
                setDataAndType(uri, safeMime)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }
            // Chooser zeigt Android-Auswahl falls mehrere Apps das MIME oeffnen koennen.
            val chooser = Intent.createChooser(intent, "Oeffnen mit").apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(chooser)
            promise.resolve(true)
        } catch (e: Exception) {
            promise.reject("OPEN_ERROR", e.message, e)
        }
    }
}
