package com.example.mysmartlab.Adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import androidx.recyclerview.widget.RecyclerView
import com.example.mysmartlab.databinding.CategoryBinding
import com.example.mysmartlab.R


class AdapterCategory(private val names: List<String>) :
    RecyclerView.Adapter<AdapterCategory.CategoryHolder>() {
    private var listener: Listener? = null
    var last: RadioButton? = null
    var  selectedRBPosition = 0
    class CategoryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val binding = CategoryBinding.bind(itemView)
        val objectCategory = binding.objectCategoryName
    }

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

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

    override fun onBindViewHolder(holder: CategoryHolder, position: Int) {
        val item = holder.objectCategory
        item.text = (names[position])
        if (position == 0) last = item
        item.isChecked = selectedRBPosition == position
        item.setOnClickListener {
            selectedRBPosition = holder.adapterPosition
            if (listener != null) {
                listener!!.onClick(position, item)
            }
            notifyDataSetChanged()
        }
    }

    fun setOnClickListener(listener: Listener) {
        this.listener = listener
    }


    interface Listener {
        fun onClick(position: Int, item: RadioButton)
    }

}
