package com.khmer9.sbcmain.screen.main

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast

class PackageChangeReceiver : BroadcastReceiver() {
    companion object {
        var token: String? = null
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        // fetching package names from extras
        val packageName = intent?.data?.encodedSchemeSpecificPart
        when (intent?.action) {
            Intent.ACTION_PACKAGE_FULLY_REMOVED -> Toast.makeText(
                context,
                "${packageName.toString()} uninstalled",
                Toast.LENGTH_SHORT
            ).show()

            Intent.ACTION_PACKAGE_CHANGED -> {
                Toast.makeText(
                    context,
                    "${packageName.toString()} installed",
                    Toast.LENGTH_SHORT
                ).show()

                try {
                    val launchIntent = context?.packageManager?.getLaunchIntentForPackage(packageName.toString())
                    if (launchIntent != null) {
                        if (token != null) {
                            launchIntent?.putExtra("token", token)
                            context?.startActivity(launchIntent)
                        }
                    }
                } catch (e: Exception) {
                }
            }
        }
    }
}