package com.yidian.bcommon.utils

import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import java.util.regex.Pattern


/**
 * 字符串相关的工具类
 */
object StringUtils {

  /**
   * 筛选关键字并设置变色
   */
  fun matcherSearchText(color: Int, text: String, keyword: String): SpannableStringBuilder {
    val ss = SpannableStringBuilder(text)
    val matcher = Pattern.compile(keyword).matcher(ss)
    while (matcher.find()) {
      val start = matcher.start()
      val end = matcher.end()
      ss.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    return ss
  }

  interface RichClickListener {
    fun onClick()
  }

  /**
   * 筛选关键字并设置颜色和点击事件
   */
  fun setRichText(textView: TextView, content: String, target:String, color: Int, listener: RichClickListener) {
    val stringBuilder = SpannableStringBuilder(content)
    val matcher = Pattern.compile(target).matcher(content)
    while (matcher.find()) {
      val start = matcher.start()
      val end = matcher.end()
      stringBuilder.setSpan(object : ClickableSpan() {
        override fun onClick(widget: View) {
          listener.onClick()
        }

        override fun updateDrawState(ds: TextPaint) {
          super.updateDrawState(ds)
          ds.isUnderlineText = false
          ds.color = color
        }

      }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    textView.text = stringBuilder
    textView.movementMethod = LinkMovementMethod.getInstance()
  }

}
