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

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import coil.transform.CircleCropTransformation
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.ItemLiveRoomProfileBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.extensions.loadUrl
import kr.co.vividnext.sodalive.live.room.info.LiveRoomMember

class LiveRoomProfileListAdapter : RecyclerView.Adapter<LiveRoomProfileListAdapter.ViewHolder>() {
    inner class ViewHolder(
        private val binding: ItemLiveRoomProfileBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: LiveRoomMember) {
            binding.ivProfile.loadUrl(item.profileImage) {
                crossfade(true)
                placeholder(R.drawable.ic_place_holder)
                transformations(CircleCropTransformation())

                if (activeSpeakers.contains(item.id.toInt())) {
                    binding.ivBg.visibility = View.VISIBLE
                } else {
                    binding.ivBg.visibility = View.GONE
                }

                if (muteSpeakers.contains(item.id.toInt())) {
                    binding.ivMute.visibility = View.VISIBLE
                } else {
                    binding.ivMute.visibility = View.GONE
                }

                val ivMuteLp = binding.ivMute.layoutParams
                ivMuteLp.width = 28f.dpToPx().toInt()
                ivMuteLp.height = 28f.dpToPx().toInt()
                binding.ivMute.layoutParams = ivMuteLp
            }

            binding.tvNickname.text = item.nickname
        }
    }

    private val items = mutableListOf<LiveRoomMember>()
    val activeSpeakers = mutableSetOf<Int>()
    val muteSpeakers = mutableSetOf<Int>()
    var managerId: Long = -1

    fun updateList(items: List<LiveRoomMember>) {
        items.let {
            val diffCallback = LiveRoomMemberResponseDiffUtilCallback(this.items, items)
            val diffResult = DiffUtil.calculateDiff(diffCallback)

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

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

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

    override fun getItemCount() = items.count()
}
