package com.aiosman.ravenow.model

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log

data class UpdateInfo(
    val versionCode: Int,
    val versionName: String,
    val updateContent: String,
    val downloadUrl: String,
    val forceUpdate: Boolean
)

class ApkInstallReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("ApkInstallReceiver", "onReceive() called") // 添加日志输出
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == intent.action) {
            Log.d("ApkInstallReceiver", "Download complete") // 添加日志输出
            val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

            // 方案二：通过 DownloadManager 的 API 获取 Uri
             val uri = downloadManager.getUriForDownloadedFile(downloadId)
             if (uri != null) {
                 installApk(context, uri)
             }
        }
    }

    private fun installApk(context: Context, uri: Uri) {
        Log.d("ApkInstallReceiver", "installApk() called with: context = $context, uri = $uri") // 添加日志输出
        val installIntent = Intent(Intent.ACTION_VIEW)
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive")
        installIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
        context.startActivity(installIntent)
    }
}