package com.gh.gamecenter.xapk.pi

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.content.pm.PackageInstaller.Session
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi

class SplitPackagesInstaller(
    private val sessionId: Int
) : IPackageInstaller {

    override fun install(context: Context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return
        }
        val installer = context.packageManager.packageInstaller
        val session = installer.openSession(sessionId)
        // 监听安装回调的组件，可以是Activity、Service或者是BroadcastReceiver
        val intent = Intent(context, InstallerReceiver::class.java)
        val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        } else {
            PendingIntent.FLAG_UPDATE_CURRENT
        }
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flags)
        // 提交数据流并执行安装
        session.commit(pendingIntent.intentSender)
        session.close()
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    class InstallerReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)
            val statusMessage = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
            when (status) {
                PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                    intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)?.also {
                        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        context.startActivity(it)
                    }
                }

                PackageInstaller.STATUS_SUCCESS,
                PackageInstaller.STATUS_FAILURE,
                PackageInstaller.STATUS_FAILURE_ABORTED,
                PackageInstaller.STATUS_FAILURE_BLOCKED,
                PackageInstaller.STATUS_FAILURE_CONFLICT,
                PackageInstaller.STATUS_FAILURE_INCOMPATIBLE,
                PackageInstaller.STATUS_FAILURE_INVALID,
                PackageInstaller.STATUS_FAILURE_STORAGE -> Log.d(
                    "XApkInstallReceiver",
                    "安装失败，状态码：$status 消息：$statusMessage"
                )

                else -> Log.d(
                    "XApkInstallReceiver",
                    "其他状态，返回码:${intent.flags} 状态码：$status 消息：$statusMessage"
                )
            }
        }
    }
}