package com.base.pdfreaderallpdfreader.ui.view

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.databinding.DialogStoragePermissionBinding
import com.base.pdfreaderallpdfreader.utils.ActivityLauncher
import com.base.pdfreaderallpdfreader.utils.PermissionUtils.requestStoragePermission
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog

object MainDialog {


    fun Context.showStoragePermission(
        launcher: ActivityLauncher,
        launcherAction: ((flag: Boolean) -> Unit)? = null,
        noLauncherAction: (() -> Unit)? = null,
        dismissAction: (() -> Unit)? = null,
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val binding = DialogStoragePermissionBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)

        dialog.show()

        val parentView = binding.root.parent as View
        val behavior = BottomSheetBehavior.from(parentView)
        //展开
        behavior.state = BottomSheetBehavior.STATE_EXPANDED

        binding.tvAllow.setOnClickListener {
            dialog.dismiss()
            requestStoragePermission(launcher) {
                launcherAction?.invoke(it)
            }
        }
        dialog.setOnDismissListener {
            dismissAction?.invoke()
        }
        val text = "To read and edit documents on your device, please allow PDF Reader to access all your files"
        val redText = "PDF Reader"
        val spannableString = SpannableString(text)
        val startIndex = text.indexOf(redText)
        val endIndex = startIndex + redText.length

        spannableString.setSpan(
            ForegroundColorSpan(Color.parseColor("#6DA9FD")),
            startIndex,
            endIndex,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.tvTip.text = spannableString

        return dialog

    }
}