package com.secspace.sms.util

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import java.util.regex.Pattern

object SpannableStringUtil {
    fun getPhoneNumberWithBody(strTel: String): SpannableString {
        val ss = SpannableString(strTel)
        val list = getNumbers(strTel)
        if (list.isNotEmpty()) {
            for (i in list.indices) {
                ss.setSpan(
                    object : ClickableSpan() {
                        override fun updateDrawState(ds: TextPaint) {
                            super.updateDrawState(ds)
                            ds.color = Color.BLUE //设置文件颜色
                            ds.isUnderlineText = true //设置下划线
                        }

                        override fun onClick(widget: View) {
                        }
                    },
                    strTel.indexOf(list[i]),
                    strTel.indexOf(list[i]) + 11,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        return ss
    }


    /**
     * 将字符串中的电话号码设置点击事件和下划线
     *
     * @param context
     * @param tv
     * @param strTel
     */
    fun setTelUrl(context: Context?, tv: TextView, strTel: String) {
        getPhoneNumberWithBody(strTel)
        tv.highlightColor = Color.TRANSPARENT //设置点击后的颜色为透明，否则会一直出现高亮
        tv.text = getPhoneNumberWithBody(strTel)
        tv.movementMethod = LinkMovementMethod.getInstance() //开始响应点击事件
    }


    /**
     * 从字符串中查找电话号码字符串
     */
    fun getNumbers(content: String?): List<String> {
        val digitList: MutableList<String> = ArrayList()
        val p = Pattern.compile("(\\d{11})")
        val m = p.matcher(content)
        while (m.find()) {
            val find = m.group(1).toString()
            digitList.add(find)
        }
        return digitList
    }
}
