package com.zxhy.simplefilesmanager.simplejoke

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import java.io.File

/**
 * 访问所有文件权限设置界面
 * https://blog.csdn.net/qq_17766199/article/details/115351949
 */
object IntentEx {
    @RequiresApi(Build.VERSION_CODES.R)
    fun settingManageExternalStorage(uri: Uri? = null): Intent {
        val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri)
//    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        return intent
    }

    //权限设置界面
    fun goToPermissionSettings(context: Context, activityLauncher: JoActivityJoLauncher) {
        val intent = appSettingsIntent(context.packageName)
        activityLauncher.launch(intent)
    }

    /**
     * 应用设置页面意图
     */
    fun appSettingsIntent(packageName: String): Intent {
        return Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            .setData(Uri.fromParts("package", packageName, null))
    }

    fun systemActionView(context: Context, path: String, tittle: String = "IMAGE") {
        val uri =
            FileProvider.getUriForFile(context, "${context.packageName}.provider", File(path))
        val intent = Intent().apply {
            action = Intent.ACTION_VIEW
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            val type = if (tittle == "IMAGE") "image/*" else "video/*"
            setDataAndType(uri, type)
        }
        context.startActivity(intent)
    }

    fun systemActionView(context: Context, uri: Uri, tittle: String = "IMAGE") {
        val intent = Intent().apply {
            action = Intent.ACTION_VIEW
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            setDataAndType(uri, if (tittle == "IMAGE") "image/*" else "video/*")
        }
        context.startActivity(intent)
    }
}
