package kr.co.vividnext.sodalive.live.room.donation

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import kr.co.vividnext.sodalive.databinding.ItemLiveRoomDonationMessageBinding

class LiveRoomDonationMessageAdapter(
    private val onClickDeleteMessage: (String) -> Unit,
    private val copyMessage: (String) -> Unit
) : RecyclerView.Adapter<LiveRoomDonationMessageAdapter.ViewHolder>() {

    private var items = mutableListOf<LiveRoomDonationMessage>()

    inner class ViewHolder(
        private val binding: ItemLiveRoomDonationMessageBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        @SuppressLint("SetTextI18n")
        fun bind(item: LiveRoomDonationMessage) {
            binding.tvNickname.text = "${item.nickname}님이"
            binding.tvCanMessage.text = item.canMessage
            binding.tvDonationMessage.text = "\"${item.donationMessage}\""
            binding.ivDelete.setOnClickListener { onClickDeleteMessage(item.uuid) }

            binding.root.setOnClickListener { copyMessage(item.donationMessage) }
        }
    }

    fun update(items: List<LiveRoomDonationMessage>) {
        items.let {
            val diffCallback = LiveRoomDonationMessageDiffUtilCallback(this.items, items)
            val diffResult = DiffUtil.calculateDiff(diffCallback)

            this.items.run {
                clear()
                addAll(it)
                diffResult.dispatchUpdatesTo(this@LiveRoomDonationMessageAdapter)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemLiveRoomDonationMessageBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int {
        return items.size
    }
}
