package com.gh.gamecenter.game.horizontal

import android.text.TextUtils
import android.view.ViewTreeObserver
import android.widget.TextView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.databinding.GameHorizontalSimpleItemBinding
import com.gh.gamecenter.feature.entity.GameEntity

class GameHorizontalSimpleItemViewHolder(val binding: GameHorizontalSimpleItemBinding) :
    BaseRecyclerViewHolder<GameEntity>(binding.root) {
    companion object {
        @JvmStatic
        fun setHorizontalNameAndGravity(view: TextView, name: String?) {
            view.text = name
            view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    view.viewTreeObserver.removeOnGlobalLayoutListener(this);
                    val newText = autoSplitText(view);
                    if (!TextUtils.isEmpty(newText)) {
                        view.text = newText;
                    }
                }
            })
        }

        // 手动把文本进行换行处理
        private fun autoSplitText(tv: TextView): String? {
            try {
                val rawText = tv.text.toString()
                val tvPaint = tv.paint
                val width = tv.width
                if (width == 0) return null // 为零时，执行以下代码会进入死循环
                val tvWidth = (width - tv.paddingLeft - tv.paddingRight).toFloat()
                val rawTextLines = rawText
                    .replace("\r".toRegex(), "")
                    .split("\n".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                val sbNewText = StringBuilder()
                for (rawTextLine in rawTextLines) {
                    if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                        sbNewText.append(rawTextLine)
                    } else {
                        var lineWidth = 0f
                        var cnt = 0
                        while (cnt != rawTextLine.length) {
                            val ch = rawTextLine[cnt]
                            lineWidth += tvPaint.measureText(ch.toString())
                            if (lineWidth <= tvWidth) {
                                sbNewText.append(ch)
                            } else {
                                sbNewText.append("\n")
                                lineWidth = 0f
                                --cnt
                            }
                            ++cnt
                        }
                    }
                    sbNewText.append("\n")
                }
                if (!rawText.endsWith("\n")) {
                    sbNewText.deleteCharAt(sbNewText.length - 1)
                }
                return sbNewText.toString()
            } catch (ignore: Exception) {

            }
            return ""
        }
    }
}