package com.easy.clean.utils

import android.Manifest
import android.app.Activity
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import com.easy.clean.utils.IntentUtils.intentAppDetailsSettings

object PermissionUtils {

    //region 打电话
    fun Context.checkCallPhonePermission(): Boolean {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
    }
    //endregion

    //region联系人
    fun Context.checkContactsReadPermission(): Boolean {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
    }

    fun Context.checkContactsWritePermission(): Boolean {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
    }
    //endregion

    //region 相机
    fun Context.checkCameraPermission(): Boolean {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
    }
    //endregion

    //region 通知
    fun Context.areNotificationsEnabled(): Boolean {
        val notificationManager =
            this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val flag = notificationManager.areNotificationsEnabled()
        return flag
    }

    fun Context.checkNotificationPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
        } else {
            return true
        }
    }

    fun Context.requestNotificationPermission(
        launcher: ActivityLauncher,
        result: (Boolean) -> Unit
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val array = arrayOf(Manifest.permission.POST_NOTIFICATIONS)
            launcher.launch(array) { permissions ->
                val flag = permissions.values.all { it }
                if (!flag) notificationSettings(launcher, result)
            }
        } else {
            notificationSettings(launcher, result)
        }
    }

    fun Context.notificationSettings(
        launcher: ActivityLauncher,
        result: (Boolean) -> Unit
    ) {
        val intent = Intent()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
        } else {
            intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
            intent.putExtra("app_package", packageName)
        }
        launcher.launch(intent) {
            result.invoke(checkNotificationPermission())
        }
    }
    //endregion

    //region 储存
    fun Context.checkStorePermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            val readPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            val writePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    fun Context.requestStoragePermission(
        launcher: ActivityLauncher,
        jumpAction: (() -> Unit)? = null,
        result: (flag: Boolean) -> Unit
    ) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val intent =
                Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.addCategory("android.intent.category.DEFAULT")
            intent.data = Uri.parse("package:${packageName}")
            jumpAction?.invoke()
            launcher.launch(intent) {
                result.invoke(checkStorePermission())
            }
        } else {
            launcher.launch(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { map ->
                result(map.values.all { it })
            }
        }

    }

    //endregion

    //region 定位
    fun Context.checkAllLocationPermission(): Boolean {
        return checkLocationPermission() && checkBackgroundLocationPermission()
    }

    fun Context.checkLocationPermission(): Boolean {

        val fineLocationPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val accessCoarsePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        return fineLocationPermission == PackageManager.PERMISSION_GRANTED && accessCoarsePermission == PackageManager.PERMISSION_GRANTED;
    }

    fun Activity.checkLocationPermissionDeniedByUser(): Boolean {

        val deniedByUser1 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val deniedByUser2 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        LogEx.logDebug("checkLocationPermissionDeniedByUser", "accessCoarsePermission=$deniedByUser1")
        LogEx.logDebug("checkLocationPermissionDeniedByUser", "fineLocationPermission=$deniedByUser2")

        return deniedByUser1 && deniedByUser2
    }

    fun Context.checkBackgroundLocationPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_BACKGROUND_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            true
        }
    }

    fun Activity.checkBackgroundLocationPermissionDeniedByUser(): Boolean {
        val deniedByUser1 =
            !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        return deniedByUser1
    }

    fun Activity.requestLocationAllowAllTime(
        launcher: ActivityLauncher,
        jumpOutAction: (() -> Unit)? = null,//跳转到设置
        permissionAllowCallBack: (() -> Unit)? = null//权限同意
    ) {

        val TAG = "requestLocationAllowAllTime"

        launcher.launch(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
            )
        ) { map ->
            val result = map.values.all { it }
            LogEx.logDebug(TAG, "定位权限回调 result=$result")
            if (result) {
                //跳转到后台位置设置
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    launcher.launch(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) { map ->
                        val backLocationResult = map.values.all { it }
                        LogEx.logDebug(TAG, "后台位置权限回调 backLocationResult=$backLocationResult")
                        if (backLocationResult) {
//                            toast("权限请求完毕")
                            permissionAllowCallBack?.invoke()
                        } else {
                            val userBackLocationDeny = this.checkBackgroundLocationPermissionDeniedByUser()
                            LogEx.logDebug(TAG, "userBackLocationDeny userBackLocationDeny=$userBackLocationDeny 跳转设置")
                            if (userBackLocationDeny) {
                                jumpOutAction?.invoke()
                                launcher.launch(intentAppDetailsSettings(this))
                            }
                        }
                    }
                } else {
                    permissionAllowCallBack?.invoke()
//                    toast("权限请求完毕")
                }
            } else {
                val userDeny = checkLocationPermissionDeniedByUser()
                LogEx.logDebug(TAG, "userDeny userDeny=$userDeny 跳转设置")
                if (userDeny) {
                    jumpOutAction?.invoke()
                    launcher.launch(intentAppDetailsSettings(this))
                }
            }
        }
    }

    //endregion

}