package com.gh.common.view

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.children
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.visibleIf

/**
 *  单游戏卡片标签样式专用
 *  根据宽度展示标签个数，最多展示三个标签
 */
class SingleCardTagContainerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
) : LinearLayout(context, attrs) {

    private val childViews = arrayListOf<TextView>()

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        children.forEach {
            // 父容器不限制子View的宽度
            it.measure(MeasureSpec.UNSPECIFIED, heightMeasureSpec)
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        // 如果有显示不完整的标签，直接隐藏
        children.forEach {
            it.visibleIf(it.right <= width)
        }
    }

    fun setData(tags: List<String>) {
        removeAllViews()
        tags.forEachIndexed { index, tag ->
            if (index < 3) {
                // 缓存子View 避免频繁创建新View
                val tvTag = childViews.getOrNull(index) ?: TextView(context).also { childViews.add(it) }
                if (index == 0) {
                    tvTag.text = tag
                } else {
                    tvTag.text = "$DELIMITER$tag"
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    tvTag.setTextAppearance(com.gh.gamecenter.common.R.style.TextCaption2)
                } else {
                    tvTag.setTextAppearance(context, com.gh.gamecenter.common.R.style.TextCaption2)
                }
                tvTag.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
                addView(tvTag)
            }
        }
    }

    companion object {
        private const val DELIMITER = "·"
    }
}