package com.adealink.weparty.room.chat.adapter

import android.os.Build
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.TypefaceSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.ext.findAndSetSpan
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.DEFAULT_FONT_BOLD
import com.adealink.weparty.commonui.recycleview.adapter.BindingViewHolder
import com.adealink.weparty.commonui.recycleview.adapter.multitype.ItemViewBinder
import com.adealink.weparty.module.room.chat.data.EnterRoomMessage
import com.adealink.weparty.room.R
import com.adealink.weparty.room.chat.listener.IMessageOperaListener
import com.adealink.weparty.room.databinding.ItemMessageEnterRoomBinding
import com.adealink.weparty.R as APP_R

/**
 */
class EnterRoomMessageViewBinder(
    val listener: IMessageOperaListener,
    val fragment: Fragment,
) : ItemViewBinder<EnterRoomMessage, EnterRoomMessageViewBinder.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder, item: EnterRoomMessage) {
        holder.update(item)
    }

    override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
        return ViewHolder(ItemMessageEnterRoomBinding.inflate(inflater, parent, false))
    }

    inner class ViewHolder(binding: ItemMessageEnterRoomBinding) :
        BindingViewHolder<ItemMessageEnterRoomBinding>(binding) {

        private var message: EnterRoomMessage? = null

        fun update(message: EnterRoomMessage) {
            this.message = message
            //消息内容
            val userName = message.barrage.sender.userName
            val text = getCompatString(R.string.room_enter_room_message, userName)
            binding.clBg.onClick {
                val uid = message.barrage.sender.userID
                if (uid.isNotEmpty()) {
                    listener.onAvatarClick(message.barrage.sender.userID)
                }
            }
            binding.msg.text = SpannableStringBuilder(text).apply {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    findAndSetSpan(TypefaceSpan(DEFAULT_FONT_BOLD), userName)
                }
                findAndSetSpan(
                    ForegroundColorSpan(getCompatColor(APP_R.color.color_FF35F3F0)),
                    userName
                )
            }

        }

    }

}