package com.seven.ikar.kotlin.core.update

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.os.Build

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

        val preferences = ArgusAppUpdatePreferences(context)
        val packageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)
            ?: intent.getStringExtra(ArgusAppUpdateInstaller.EXTRA_PACKAGE_NAME)
        val releaseVersion = intent.getStringExtra(ArgusAppUpdateInstaller.EXTRA_RELEASE_VERSION)
        val versionCode = intent.getLongExtra(ArgusAppUpdateInstaller.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)

        when (status) {
            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                preferences.saveInstallerEvent(
                    state = AppUpdateInstallerEventState.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 = AppUpdateInstallerEventState.Installed,
                    packageName = packageName,
                    releaseVersion = releaseVersion,
                    versionCode = versionCode,
                    detail = statusMessage ?: "Обновление установлено."
                )
                ArgusAppUpdateCache.deleteAllDownloads(context)
            }

            else -> {
                preferences.saveInstallerEvent(
                    state = AppUpdateInstallerEventState.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)
        }
}
