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.ProductInfo
import com.squareup.picasso.Picasso

class ProductAdapter(var cardList: MutableList<ProductInfo>, private val listener: ProductAdapter.OnItemClickListener) : RecyclerView.Adapter<ProductAdapter.ViewHolder>() {
    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

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

    override fun onBindViewHolder(holder: ProductAdapter.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/product/image/" + currentItem.filename).into(holder.imageView)
        }
        holder.subTitleTextView.text = currentItem.desc
        holder.titleTextView.text = currentItem.name
        holder.priceTextView.text = "$" + currentItem.price
    }

    override fun getItemCount() = cardList.size

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

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