package com.sambath.kunkhmer.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.config.Config
import com.sambath.kunkhmer.remote.LivesInfo
import com.squareup.picasso.Picasso

class LivesAdapter(var cardList: List<LivesInfo>, private val listener: OnItemClickListener) : RecyclerView.Adapter<LivesAdapter.ViewHolder>() {

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LivesAdapter.ViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.layout_lives_item_card, parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: LivesAdapter.ViewHolder, position: Int) {
        val currentItem = cardList[position]

        if(currentItem.filename == null) {
            Picasso.get().load(R.drawable.default_background).into(holder.imageView)
        } else {
            Picasso.get()
                .load(Config.BASE_URL + "/v1/live/image/" + currentItem.filename)
                .error(R.drawable.default_background) // Set the default image resource
                .into(holder.imageView)
        }

        holder.subTitleTextView.text = currentItem.desc
        holder.titleTextView.text = currentItem.name
    }

    override fun getItemCount() = cardList.size

    inner class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
        val subTitleTextView: TextView = itemView.findViewById(R.id.subTitleTextView)
        val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)

        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(position)
                }
            }
        }
    }
}