package com.gh.common.dialog

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.*
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.databinding.DialogPrivacyProtocolNewBinding
import com.gh.gamecenter.entity.DialogEntity

class NewPrivacyPolicyDialogFragment : BaseDialogFragment() {

    private var mCallBack: ((isSuccess: Boolean) -> Unit)? = null
    private val mBinding by lazy { DialogPrivacyProtocolNewBinding.inflate(layoutInflater) }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        updateView()
    }

    private fun updateView() {
        val contentText = SpannableStringBuilder(
            "1.您可以通过《光环助手隐私政策》以及《儿童隐私保护声明》，了解我们如何收集、使用、存储、保护、对外提供您的个人信息以及您享有的权利\n" +
                    "2.您可以通过《接入第三方SDK目录》了解本产品接入的第三方SDK的具体信息\n" +
                    "3.您可以通过《应用权限列表》了解权限申请与使用情况说明\n" +
                    "4.如果您是14周岁以下的未成年人，您需要和您监护人一起仔细阅读《儿童隐私保护声明》，并在征得您监护人同意后，使用我们的产品、服务或向我们提供信息"
        )

        val privacyPolicyText = "《光环助手隐私政策》"
        val childrenPrivacyPolicyText = "《儿童隐私保护声明》"
        val thirdPartySdkText = "《接入第三方SDK目录》"
        val permissionListText = "《应用权限列表》"

        val hypertextList = arrayListOf(
            privacyPolicyText,
            childrenPrivacyPolicyText,
            thirdPartySdkText,
            permissionListText
        )

        val positionListPairList = arrayListOf<Pair<Int, Int>>()

        for (hypertext in hypertextList) {
            var start = 0
            var index = 0
            while (index != -1) {
                index = contentText.indexOf(hypertext, start)
                start = index + hypertext.length
                if (index != -1) {
                    positionListPairList.add(Pair(index, start))
                }
            }
        }

        for (hypertextPositionPair in positionListPairList) {
            contentText.setSpan(object : ClickableSpan() {
                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ContextCompat.getColor(requireContext(), R.color.theme_font)
                    ds.isUnderlineText = false
                }

                override fun onClick(widget: View) {
                    val privacyPolicyUrl = requireContext().getString(R.string.privacy_policy_url)
                    val childrenPrivacyPolicyUrl = requireContext().getString(R.string.children_policy_url)
                    val thirdPartySdkUrl = requireContext().getString(R.string.sdk_list_url)
                    val permissionListUrl = requireContext().getString(R.string.permission_and_usage_url)

                    val selectedUrl =
                        when (contentText.substring(hypertextPositionPair.first, hypertextPositionPair.second)) {
                            privacyPolicyText -> privacyPolicyUrl
                            childrenPrivacyPolicyText -> childrenPrivacyPolicyUrl
                            thirdPartySdkText -> thirdPartySdkUrl
                            permissionListText -> permissionListUrl
                            else -> ""
                        }

                    DirectUtils.directToExternalBrowser(requireContext(), selectedUrl)
                }
            }, hypertextPositionPair.first, hypertextPositionPair.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        mBinding.contentTv.movementMethod = CustomLinkMovementMethod.getInstance()
        mBinding.contentTv.text = contentText

        mBinding.refuseTv.setOnClickListener {
            mCallBack?.invoke(false)
            dismissAllowingStateLoss()
        }
        mBinding.agreeTv.setOnClickListener {
            mCallBack?.invoke(true)
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(false)
        createDialog.setOnKeyListener(object : DialogInterface.OnKeyListener {
            override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true
                }
                return false
            }
        })

        val window = createDialog.window
        window?.setGravity(Gravity.CENTER)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = 300F.dip2px()
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    companion object {
        const val KEY_DATA = "data"

        @JvmStatic
        fun show(
            activity: FragmentActivity,
            privacyPolicyEntity: DialogEntity.PrivacyPolicyEntity? = null,
            callBack: ((isSuccess: Boolean) -> Unit)?
        ) {
            var privacyDialogFragment =
                activity.supportFragmentManager.findFragmentByTag(NewPrivacyPolicyDialogFragment::class.java.name) as? NewPrivacyPolicyDialogFragment
            if (privacyDialogFragment != null) {
                privacyDialogFragment.mCallBack = callBack
                val transaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
                transaction.show(privacyDialogFragment)
                transaction.commit()
            } else {
                privacyDialogFragment = NewPrivacyPolicyDialogFragment().apply {
                    mCallBack = callBack
                }
            }
            privacyDialogFragment.arguments = Bundle().apply {
                putParcelable(KEY_DATA, privacyPolicyEntity)
            }
            privacyDialogFragment.show(
                activity.supportFragmentManager,
                NewPrivacyPolicyDialogFragment::class.java.name
            )
        }
    }
}