package com.base.browserwhite.utils

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.widget.Toast

@SuppressLint("QueryPermissionsNeeded")
object IntentEx {

    fun Context.shareAction(uri: Uri, mimeType: String) {
        val shareIntent = Intent().apply {
            action = Intent.ACTION_SEND
            type = mimeType
            putExtra(Intent.EXTRA_STREAM, uri)
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            // 可以添加更多额外信息，如主题、文本等
        }
        val chooserIntent = Intent.createChooser(shareIntent, "Share File")
        if (shareIntent.resolveActivity(this.packageManager) != null) {
            this.startActivity(chooserIntent)
        } else {
            Toast.makeText(this, "no app can share the file", Toast.LENGTH_SHORT).show()
        }
    }

    fun Context.viewDocumentAction(uri: Uri, mimeType: String) {
        val viewIntent = Intent().apply {
            action = Intent.ACTION_VIEW
            setDataAndType(uri, mimeType)
            flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            // 可以添加更多额外信息，如主题、文本等
        }
        val chooserIntent = Intent.createChooser(viewIntent, "Share File")
        if (chooserIntent.resolveActivity(this.packageManager) != null) {
            this.startActivity(viewIntent)
        } else {
            Toast.makeText(this, "no app can open the file", Toast.LENGTH_SHORT).show()
        }
    }

    fun Context.viewAudioAction(uri: Uri, mimeType: String) {
        // 构建一个Intent，使用ACTION_VIEW操作
        val intent = Intent(Intent.ACTION_VIEW)

        intent.setDataAndType(uri, mimeType)

        // 设置标志，以便Intent可以选择其他应用来完成这个操作
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        // 尝试启动Intent
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        } else {
            // 如果没有应用可以处理这个Intent，可以在这里处理错误
            // 例如，显示一个Toast消息
            Toast.makeText(this, "no app can play the audio", Toast.LENGTH_SHORT).show()
        }
    }

    fun Context.installAokAction(uri: Uri) {
        val installIntent = Intent(Intent.ACTION_VIEW)
        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        installIntent.setDataAndType(uri, "application/vnd.android.package-archive")
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(installIntent)
    }
}