package com.gh.gamecenter.gamedetail.dialog

import android.content.Context
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.R
import com.gh.gamecenter.databinding.ItemGameDetailBigEventBinding
import com.gh.gamecenter.gamedetail.entity.BigEvent

class GameBigEventAdapter(
    val context: Context,
    val bigEvents: List<BigEvent>,
    val gameName: String,
    val mEntrance: String
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return GameBigEventViewHolder(parent.toBinding())
    }

    override fun getItemCount(): Int = bigEvents.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val bigEvent = bigEvents[position]
        if (holder is GameBigEventViewHolder) {
            holder.binding.timeTv.text = TimeUtils.getFormatTime(bigEvent.time)
            if (bigEvent.link == null) {
                holder.binding.contentTv.text = bigEvent.content
            } else {
                val content = "${bigEvent.content} ${bigEvent.link?.value}"
                val builder = SpannableStringBuilder(content)
                builder.setSpan(object : ClickableSpan() {
                    override fun updateDrawState(ds: TextPaint) {
                        ds.color = ContextCompat.getColor(context, R.color.theme_font)
                        ds.isUnderlineText = true
                    }

                    override fun onClick(widget: View) {
//                        MtaHelper.onEvent("游戏大事件", "点击链接", "${gameName}+${bigEvent.link?.value}")
                        DirectUtils.directToLinkPage(context, bigEvent.link!!, mEntrance, "游戏大事件弹窗")
                    }
                }, bigEvent.content.length + 1, content.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                holder.binding.contentTv.movementMethod = LinkMovementMethod()
                holder.binding.contentTv.text = builder
            }
        }
    }

    class GameBigEventViewHolder(var binding: ItemGameDetailBigEventBinding) : RecyclerView.ViewHolder(binding.root)
}