package com.sambath.kunkhmer.adapter

import android.graphics.drawable.Drawable
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

class FighterAdapter (private val cardList: List<FighterCardItem>) : RecyclerView.Adapter<FighterAdapter.ViewHolder>()  {
    class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

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

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

        holder.imageLeft.setImageResource(currentItem.imageLeft)
        holder.imageLeftTitle.text = currentItem.imageLeftTitle
        holder.imageRight.setImageResource(currentItem.imageRight)
        holder.imageRightTitle.text = currentItem.imageRightTitle
        holder.date.text = currentItem.date
        holder.title.text = currentItem.title

        if(currentItem.favorite) {
            val drawable: Drawable? = holder.itemView.context.getDrawable(R.drawable.ic_star_filled_50)
            holder.favorite.setImageDrawable(drawable)
        } else {
            val drawable: Drawable? = holder.itemView.context.getDrawable(R.drawable.ic_star_50)
            holder.favorite.setImageDrawable(drawable)
        }

        holder.favorite.setOnClickListener{
            if (!currentItem.favorite) {
                // Perform bookmarking action
                val drawable: Drawable? = holder.itemView.context.getDrawable(R.drawable.ic_star_filled_50)
                holder.favorite.setImageDrawable(drawable)
                currentItem.favorite = true
            } else {
                // Perform unbookmarking action
                val drawable: Drawable? = holder.itemView.context.getDrawable(R.drawable.ic_star_50)
                holder.favorite.setImageDrawable(drawable)
                currentItem.favorite = false
            }
        }

    }

    override fun getItemCount() = cardList.size

    // Holds the views for adding it to image and text
    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageLeft: ImageView = itemView.findViewById(R.id.imageLeft)
        val imageLeftTitle: TextView = itemView.findViewById(R.id.titleLeft)
        val imageRight: ImageView = itemView.findViewById(R.id.imageRight)
        val imageRightTitle: TextView = itemView.findViewById(R.id.titleRight)
        val date: TextView = itemView.findViewById(R.id.tvDate)
        val title: TextView = itemView.findViewById(R.id.titleMatch)
        val favorite: ImageView = itemView.findViewById(R.id.bookmarkToggleButton)
    }
}