package com.example.pantallacompra

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class ChairAdapter (private val item : ArrayList<Asiento>): RecyclerView.Adapter<ChairAdapter.ViewHolder>()  {

    private lateinit var mListener : onItemClickListener
    private val selectedItems = ArrayList<Int>()

    fun toggleSelection(position: Int) {
        if (selectedItems.contains(position)) {
            selectedItems.remove(position)
        } else {
            selectedItems.add(position)
        }
        notifyItemChanged(position)
    }

    interface onItemClickListener{
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(listener: onItemClickListener){
        mListener=listener
    }

    class  ViewHolder(itemView: View, listener: onItemClickListener): RecyclerView.ViewHolder(itemView){
        val chair : TextView = itemView.findViewById(R.id.chair)
        init {
            itemView.setOnClickListener{
                val position=adapterPosition
                if(position!=RecyclerView.NO_POSITION){
                    (itemView.context as? ChairAdapter) ?.toggleSelection((position))
                }
            }
        }
    }

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

    override fun getItemCount(): Int {
        return item.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //holder.chair.text=item[position].noAsiento.toString()
        // val chair = item[position]
        holder.chair.text = item[position].noAsiento.toString()

        if (selectedItems.contains(position)) {
            holder.itemView.setBackgroundColor(Color.RED)
        } else {
            holder.itemView.setBackgroundColor(Color.parseColor("#225c6e"))
        }

        holder.itemView.setOnClickListener {
            toggleSelection(position)
        }
    }

}