package com.example.offlinestore1

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

class InstallReceiver : BroadcastReceiver() {

    companion object {
        const val ACTION_INSTALL_RESULT = "com.example.offlinestore1.ACTION_INSTALL_RESULT"
        const val EXTRA_PACKAGE_NAME = "extra_package_name"
        const val EXTRA_OPERATION = "extra_operation" // install / uninstall
    }

    override fun onReceive(context: Context, intent: Intent) {
        val status = intent.getIntExtra(
            PackageInstaller.EXTRA_STATUS,
            PackageInstaller.STATUS_FAILURE
        )

        val packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME).orEmpty()
        val operation = intent.getStringExtra(EXTRA_OPERATION).orEmpty()

        when (status) {
            PackageInstaller.STATUS_SUCCESS -> {
                val resultIntent = Intent(ACTION_INSTALL_RESULT).apply {
                    putExtra(EXTRA_PACKAGE_NAME, packageName)
                    putExtra(EXTRA_OPERATION, operation)
                    putExtra("success", true)
                }
                context.sendBroadcast(resultIntent)

                val msg = if (operation == "uninstall") "ההסרה הושלמה" else "ההתקנה הושלמה"
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
            }

            PackageInstaller.STATUS_PENDING_USER_ACTION -> {
                val confirmIntent = 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)
                }

                confirmIntent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                if (confirmIntent != null) {
                    context.startActivity(confirmIntent)
                }
            }

            else -> {
                val msg = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE).orEmpty()

                val resultIntent = Intent(ACTION_INSTALL_RESULT).apply {
                    putExtra(EXTRA_PACKAGE_NAME, packageName)
                    putExtra(EXTRA_OPERATION, operation)
                    putExtra("success", false)
                    putExtra("message", msg)
                }
                context.sendBroadcast(resultIntent)

                Toast.makeText(context, "הפעולה נכשלה: $msg", Toast.LENGTH_LONG).show()
            }
        }
    }
}