package com.test.mydemo3.util

import android.Manifest
import android.app.Activity
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.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.callback.RequestCallback
import com.test.mydemo3.activity.HomeActivity
import com.test.mydemo3.base.BaseActivity
import java.security.Permissions

object PermissionUtil {

    var LOCATION_PERMISSION = false
    fun requestPermission(context: Context?){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){

        }else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            val intent = Intent().apply {
                action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION
                data = Uri.fromParts("package", context?.packageName, null)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            context?.startActivity(intent)

        }else{
            val intent = Intent().apply {
                action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                data = Uri.fromParts("package", context?.packageName, null)
            }
            context?.startActivity(intent)
        }
    }

    fun checkGrantedPermission(activity: ComponentActivity?) : Boolean{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            //TODO android 14以上
            HomeActivity.isPermission = Environment.isExternalStorageManager()
            return HomeActivity.isPermission
        }else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            HomeActivity.isPermission = Environment.isExternalStorageManager()
            return HomeActivity.isPermission
        }else{
            HomeActivity.isPermission = ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            return HomeActivity.isPermission
        }
    }

    fun requestLocationPermission(context: FragmentActivity?){
        PermissionX.init(context!!).permissions(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
        ).request(RequestCallback{ allGranted, grantedList, deniedList ->
            if (allGranted){
                LOCATION_PERMISSION = true
            }else{
                LOCATION_PERMISSION = false
            }
        })
    }


}