package kr.co.vividnext.sodalive.message.text

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ItemTextMessageBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.message.GetTextMessageResponse

class TextMessageAdapter(
    private val onItemClick: (GetTextMessageResponse.TextMessageItem) -> Unit
) : RecyclerView.Adapter<TextMessageAdapter.ViewHolder>() {

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

        fun bind(item: GetTextMessageResponse.TextMessageItem) {
            if (SharedPreferenceManager.nickname == item.recipientNickname) {
                binding.ivProfile.load(item.senderProfileImageUrl) {
                    crossfade(true)
                    placeholder(R.drawable.ic_place_holder)
                    transformations(RoundedCornersTransformation(23.4f.dpToPx()))
                }

                binding.tvNickname.text = item.senderNickname
            } else {
                binding.ivProfile.load(item.recipientProfileImageUrl) {
                    crossfade(true)
                    placeholder(R.drawable.ic_place_holder)
                    transformations(RoundedCornersTransformation(23.4f.dpToPx()))
                }

                binding.tvNickname.text = item.recipientNickname
            }

            binding.tvDate.text = item.date
            binding.tvMessage.text = item.textMessage

            binding.root.setOnClickListener { onItemClick(item) }
        }
    }

    val items = mutableListOf<GetTextMessageResponse.TextMessageItem>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
        ItemTextMessageBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
    )

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

    override fun getItemCount() = items.size
}
