package xyz.kusoft.argusupdater

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build
import java.io.File

class ArgusPackageInstallerStatusReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != ArgusPackageInstaller.ACTION_PACKAGE_STATUS) {
            return
        }

        val preferences = ArgusUpdatePreferences(context)
        val packageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)
            ?: intent.getStringExtra(ArgusPackageInstaller.EXTRA_PACKAGE_NAME)
        val releaseVersion = intent.getStringExtra(ArgusPackageInstaller.EXTRA_RELEASE_VERSION)
        val versionCode = intent.getLongExtra(ArgusPackageInstaller.EXTRA_VERSION_CODE, Long.MIN_VALUE)
            .takeUnless { it == Long.MIN_VALUE }
        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
        val statusMessage = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)

        if (status != PackageInstaller.STATUS_PENDING_USER_ACTION) {
            ArgusUpdateCache(File(context.cacheDir, ArgusUpdateCache.DIRECTORY_NAME)).clear()
        }

        when (status) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                preferences.saveInstallerEvent(
                    state = ArgusInstallerEventState.ApprovalRequired,
                    packageName = packageName,
                    releaseVersion = releaseVersion,
                    versionCode = versionCode,
                    detail = statusMessage ?: "Android просит подтвердить установку обновления."
                )

                extractConfirmationIntent(intent)?.let { confirmationIntent ->
                    confirmationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(confirmationIntent)
                }
            }

            PackageInstaller.STATUS_SUCCESS -> {
                preferences.saveInstallerEvent(
                    state = ArgusInstallerEventState.Installed,
                    packageName = packageName,
                    releaseVersion = releaseVersion,
                    versionCode = versionCode,
                    detail = statusMessage ?: "Обновление установлено."
                )
            }

            else -> {
                preferences.saveInstallerEvent(
                    state = ArgusInstallerEventState.Failed,
                    packageName = packageName,
                    releaseVersion = releaseVersion,
                    versionCode = versionCode,
                    detail = statusMessage ?: "Android вернул ошибку установки: $status."
                )
            }
        }
    }

    private fun extractConfirmationIntent(intent: Intent): Intent? =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra(Intent.EXTRA_INTENT)
        }
}
