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

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.adealink.frame.util.onClick
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.TextMessage
import com.adealink.weparty.module.room.listener.IMemberInfoListener
import com.adealink.weparty.room.chat.listener.IMessageOperaListener
import com.adealink.weparty.room.databinding.ItemMessageTextBinding
import com.tencent.qcloud.tuikit.timcommon.component.face.FaceManager

/**
 */
class TextMessageViewBinder(
    val listener: IMessageOperaListener,
    val memberInfoLister: IMemberInfoListener,
    val fragment: Fragment,
) : ItemViewBinder<TextMessage, TextMessageViewBinder.ViewHolder>() {

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

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

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

        private var message: TextMessage? = null

        init {
            binding.ivAvatar.onClick {
                message?.barrage?.let {
                    listener.onAvatarClick(
                        it.sender.userID
                    )
                }
            }
        }

        fun update(message: TextMessage) {
            this.message = message
            //消息内容
            FaceManager.handlerEmojiText(
                binding.msg,
                message.getText(),
                false
            )

            //发消息用户
            val senderUserInfo = this.message?.senderUserInfo
            if (senderUserInfo == null) {
                updateMemberInfo(null, message.senderUid())
                memberInfoLister.getMemberInfo(message.senderUid()) { memberInfo ->
                    if (memberInfo?.uid == this.message?.senderUid()) {
                        updateMemberInfo(memberInfo?.avatar, memberInfo?.nickName)
                    }
                }
            } else {
                updateMemberInfo(senderUserInfo.avatar, senderUserInfo.nickName)
            }
        }

        private fun updateMemberInfo(avatar: String?, name: String?) {
            binding.ivAvatar.setImageUrl(avatar)
            binding.tvName.text = name
        }
    }

}