package com.base.browserwhite.utils

import android.app.role.RoleManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View

object RoleManagerUtils {

    fun Context.isDefaultBrowser(): Boolean {
        val testIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"))
        val resolveInfo = packageManager.resolveActivity(testIntent, 0)
        return resolveInfo != null && resolveInfo.activityInfo.packageName == packageName
    }

    fun Context.requestRoleBrowser(launcher: ActivityLauncher, callBack: (() -> Unit)? = null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val roleManager = getSystemService(RoleManager::class.java) as RoleManager
            if (!roleManager.isRoleAvailable("android.app.role.BROWSER")) {
                val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
                launcher.launch(intent) {
                    callBack?.invoke()
                }
            } else if (roleManager.isRoleHeld("android.app.role.BROWSER")) {
                val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
                launcher.launch(intent) {
                    callBack?.invoke()
                }
            } else {
                val intent = roleManager.createRequestRoleIntent("android.app.role.BROWSER")
                launcher.launch(intent) {
                    callBack?.invoke()
                }
            }

        } else {
            val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
            launcher.launch(intent) {
                callBack?.invoke()
            }
        }
    }
}