package com.smplayer.smplayer

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.FileProvider
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File


class ApkInstallerBridge(
    private val context: Context,
    flutterEngine: FlutterEngine,
) {
    companion object {
        private const val CHANNEL_NAME = "smplayer/apk_installer"
    }

    private val methodChannel = MethodChannel(
        flutterEngine.dartExecutor.binaryMessenger, CHANNEL_NAME
    )

    init {
        methodChannel.setMethodCallHandler { call, result ->
            when (call.method) {
                "installApk" -> {
                    val filePath = call.argument<String>("path")
                    if (filePath.isNullOrEmpty()) {
                        result.error("INVALID_PATH", "APK file path is null or empty", null)
                        return@setMethodCallHandler
                    }
                    try {
                        launchApkInstall(filePath)
                        result.success(true)
                    } catch (exception: Exception) {
                        result.error(
                            "INSTALL_FAILED",
                            exception.message ?: "Failed to launch APK installer",
                            null,
                        )
                    }
                }

                "canRequestInstall" -> {
                    val canRequest = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        context.packageManager.canRequestPackageInstalls()
                    } else {
                        true
                    }
                    result.success(canRequest)
                }

                else -> result.notImplemented()
            }
        }
    }

    private fun launchApkInstall(filePath: String) {
        val apkFile = File(filePath)
        if (!apkFile.exists()) {
            throw IllegalArgumentException("APK file does not exist: $filePath")
        }

        val authority = "${context.packageName}.fileprovider"
        val contentUri = FileProvider.getUriForFile(context, authority, apkFile)

        val installIntent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(contentUri, "application/vnd.android.package-archive")
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        context.startActivity(installIntent)
    }

    fun dispose() {
        methodChannel.setMethodCallHandler(null)
    }
}
