package com.zxhy.hfilemanagermaster.knife

import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION
import android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION
import android.net.Uri
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.contract.ActivityResultContracts
import androidx.documentfile.provider.DocumentFile
import com.shiki.koko.datafile.saf.safIntent

class Saf(activityResultCaller: ActivityResultCaller) {

    private var resultIntentAction: ((ActivityResult) -> Unit)? = null
    private val safLauncher =
        activityResultCaller.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            resultIntentAction?.invoke(it)
        }


    private fun safLaunch(
        safIntent: Intent,
        resultAction: (ActivityResult) -> Unit
    ) {
        this.resultIntentAction = resultAction
        safLauncher.launch(safIntent)
    }

    //是否持久化
    private fun isGrantUri(context: Context, uri: Uri?): Boolean {
        if (uri != null) {
            for (persistedUriPermission in context.contentResolver.persistedUriPermissions) {
                if (persistedUriPermission.uri.toString() == uri.toString()) {
                    return true
                }
            }
        }
        return false
    }

    /**
     *请求saf授权,方法用于固定的 请求uri和与之对应的持久化uri
     */
    fun requestSaf(
        context: Context,
        safUri: Uri,
        uriAction: (DocumentFile?) -> Unit
    ) {
        val persistableUri = when (safUri) {
            androidDataUri -> persistableAndroidDataUri
            else -> null
        }

        if (isGrantUri(context, persistableUri)) {
//            context.toast("已经持久化")
            uriAction.invoke(persistableUri?.let { DocumentFile.fromTreeUri(context, it) })
            return
        }
        safLaunch(safIntent(safUri)) {
            var dstFile: DocumentFile? = null
            if (it.resultCode == RESULT_OK) {
                //这种方式可以避免编码问题
                val uri = Uri.parse(it.data?.dataString)
                val writReadFlag = FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION
                //持久化权限
                context.contentResolver.takePersistableUriPermission(
                    uri, writReadFlag
                )
                dstFile = DocumentFile.fromTreeUri(context, uri)
            }
            uriAction.invoke(dstFile)
        }
    }


    /**
     *请求saf授权,该方法根据 请求Uri的生成规则 和 持久化Uri的构建规则
     * @param path 目前只测试过 :Android/data/包名
     */
    fun requestSaf(
        context: Context,
        path: String,
        uriAction: (DocumentFile?) -> Unit
    ) {
//        val safUri =
//            Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata")
        val safUri = createSafUri(path)
        val persistableUri = createSafPersistableUri(path)

        if (isGrantUri(context, persistableUri)) {
//            context.toast("已经持久化")
            uriAction.invoke(persistableUri.let { DocumentFile.fromTreeUri(context, it) })
            return
        }
        safLaunch(safIntent(safUri)) {
            var dstFile: DocumentFile? = null
            if (it.resultCode == RESULT_OK) {
                //这种方式可以避免编码问题
                //content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata%2Fcom.tencent.mtt
                val uri = Uri.parse(it.data?.dataString)
                val writReadFlag = FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION
                //持久化权限
                context.contentResolver.takePersistableUriPermission(
                    uri, writReadFlag
                )
                //这里给定的uri(用于持久化)和创建的DocumentFile的uri之间的值是不一样的
                //content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata%2Fcom.tencent.mtt/document/primary%3AAndroid%2Fdata%2Fcom.tencent.mtt
                dstFile = DocumentFile.fromTreeUri(context, uri)
            }
            uriAction.invoke(dstFile)
        }
    }

    companion object {

        //未编码路径： "content://com.android.externalstorage.documents/document/primary:Android/data"
        //编码后路径: "content://com.android.externalstorage.documents/document/primary%3AAndroid%2Fdata"
        //用于打开指定saf
        private const val documentRoot =
            "content://com.android.externalstorage.documents/document/primary"
        val androidDataUri = Uri.parse("$documentRoot${Uri.encode(":Android/data")}")

        /**
         * 创建授权uri
         * @param path :Android/data/XXX 样例
         */
        fun createSafUri(path: String): Uri {
            return Uri.parse("$documentRoot${Uri.encode(path)}")
        }


        //用于saf授权持久化
        private const val documentTreeRoot =
            "content://com.android.externalstorage.documents/tree/primary"
        private val persistableAndroidDataUri =
            Uri.parse("$documentTreeRoot${Uri.encode(":Android/data")}")

        /**
         * 创建持久化uri
         * content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata%2Fcom.tencent.mtt
         */
        fun createSafPersistableUri(path: String): Uri {
            return Uri.parse("$documentTreeRoot${Uri.encode(path)}")
        }
    }
}