package es.verdnatura.presentation.view.feature.articulo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.R
import es.verdnatura.databinding.ItemCardRowBinding
import es.verdnatura.presentation.common.OnItemCardRowClickListener
import es.verdnatura.presentation.view.feature.articulo.model.ItemCardRowVO

class ItemCardAdapter  (
    private val items: List<ItemCardRowVO>,
    private val onItemCardRowClickListener: OnItemCardRowClickListener
): RecyclerView.Adapter<ItemCardAdapter.ItemHolder> () {


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

    override fun getItemCount() =items.size

    override fun onBindViewHolder(holder: ItemHolder, position: Int) {
        holder.bind(items[position])
        if (items[position].isEditable){
            holder.binding.root.setOnClickListener {
                onItemCardRowClickListener.onItemCardRowClickListener(items[position])
            }
        }
    }


    class ItemHolder(
        val binding: ItemCardRowBinding
    ) : RecyclerView.ViewHolder(binding.root){
        private val res = binding.root.context.resources
        fun bind(item: ItemCardRowVO) {
            binding.apply {
                if (item.barcodes.isNotEmpty()){
                    item.value = ""
                    item.barcodes.forEach {
                        item.value = item.value + it.code + "\n"
                    }
                }
                this.item = item
                if (item.isEditable){
                    itemImage.visibility = View.VISIBLE
                    itemRowLayout.setBackgroundColor(ContextCompat.getColor(itemImage.context,R.color.verdnatura_black_5))
                }else{
                    itemImage.visibility = View.INVISIBLE
                    itemRowLayout.setBackgroundColor(ContextCompat.getColor(itemImage.context,R.color.verdnatura_black_9))
                }

            }
        }
    }
}