// StoragePermissionManager.kt
package com.example.initiateaphonecallapp.manager

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.util.Log
import androidx.core.content.ContextCompat

import android.Manifest
import android.content.pm.PackageManager

class StoragePermissionManager(private val context: Context) {

    private val TAG = "StoragePermissionManager"

    // 检查是否有所有文件访问权限
    fun hasAllFilesAccess(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            // Android 10 以下默认有权限
            hasReadWritePermissions()
        }
    }
    // 检查读写权限（Android 10 及以下）
    private fun hasReadWritePermissions(): Boolean {
        val readGranted = ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED

        val writeGranted = ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED

        return readGranted && writeGranted
    }
    // 请求所有文件访问权限
    fun requestAllFilesAccess(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Log.d(TAG, "请求所有文件访问权限")
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                intent.data = Uri.parse("package:${activity.packageName}")
                activity.startActivityForResult(intent, REQUEST_CODE_ALL_FILES_ACCESS)
            } catch (e: Exception) {
                Log.e(TAG, "启动权限请求失败", e)
                // 备用方案：打开应用详情页面
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.data = Uri.parse("package:${activity.packageName}")
                activity.startActivityForResult(intent, REQUEST_CODE_APP_DETAILS)
            }
        }
    }

    // 检查是否可以从设置页面返回
    fun onActivityResult(requestCode: Int, resultCode: Int): Boolean {
        return when (requestCode) {
            REQUEST_CODE_ALL_FILES_ACCESS, REQUEST_CODE_APP_DETAILS -> {
                val hasAccess = hasAllFilesAccess()
                Log.d(TAG, "权限请求返回，当前权限状态: $hasAccess")
                hasAccess
            }
            else -> false
        }
    }

    companion object {
        const val REQUEST_CODE_ALL_FILES_ACCESS = 1002
        const val REQUEST_CODE_APP_DETAILS = 1003
    }
}