package com.gh.common.xapk

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class XapkInstallReceiver : Activity() {

    companion object {
        const val KEY_PACKAGE_PATH = "package_path"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(0, 0)
        handleIntent(this, intent)

    }

    private fun handleIntent(context: Context, intent: Intent) {
        when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999)) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                val installIntent = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
                if (installIntent != null) {
                    try {
                        context.startActivity(installIntent)
                        updatePendingSessionInfoStatus(intent, XapkPendingSessionInfo.STATUS_PENDING_USER_ACTION)
                    } catch (e: Exception) {
                        // OPPO低版本会出现CONFIRM_PERMISSIONS的权限异常，这个问题无解，直接取消安装
                        updatePendingSessionInfoStatus(intent, XapkPendingSessionInfo.STATUS_INSTALL_CANCELED)
                    }
                    finish()
                }
            }
            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 -> {
                updatePendingSessionInfoStatus(intent, XapkPendingSessionInfo.STATUS_INSTALL_CANCELED)
                finish()
            }
            else -> {
                updatePendingSessionInfoStatus(intent, XapkPendingSessionInfo.STATUS_INSTALL_SUCCESS)
                finish()
            }
        }
    }

    private fun updatePendingSessionInfoStatus(intent: Intent, status: Int) {
        val installPackagePath = intent.getStringExtra(KEY_PACKAGE_PATH)
        if (!installPackagePath.isNullOrEmpty()) {
            val pendingSessionInfo = XapkInstaller.getPendingSessionInfo(installPackagePath)
            pendingSessionInfo?.updateStatus(status)
        }
    }
}