package com.fusi24.rfid.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.fusi24.rfid.data.entity.DataDetail;
import com.fusi24.rfid.databinding.RowStatusScanBinding;

import java.util.ArrayList;
import java.util.List;

public class StatusScanAdapter extends RecyclerView.Adapter<StatusScanAdapter.ViewHolder>{

    private Context context;
    private List<DataDetail> detailList;
    private OnItemSelected onItemSelected;
    public int selectedItem = -1;

    public StatusScanAdapter(Context context, OnItemSelected onItemSelected) {
        this.context = context;
        this.detailList = new ArrayList<>();
        this.onItemSelected = onItemSelected;
    }

    private void setDetailList(List<DataDetail> detailList) {
        this.detailList = detailList;
    }

    public void updateDetailList(List<DataDetail> detailList){
        setDetailList(detailList);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private RowStatusScanBinding binding;

        ViewHolder(RowStatusScanBinding itemBinding) {
            super(itemBinding.getRoot());
            this.binding = itemBinding;

            View.OnClickListener listener = v -> {
                selectedItem = getAdapterPosition();
                onItemSelected.onSelected(detailList.get(getAdapterPosition()));
                notifyDataSetChanged();
            };

            itemView.setOnClickListener(listener);
            binding.rbCommon.setOnClickListener(listener);
        }
    }


    @NonNull
    @Override
    public StatusScanAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RowStatusScanBinding itemBinding = RowStatusScanBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ViewHolder(itemBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull StatusScanAdapter.ViewHolder holder, int position) {
        DataDetail detail = detailList.get(position);
        holder.binding.rbCommon.setText(detail.getName());
        holder.binding.rbCommon.setChecked(position == selectedItem);
    }

    @Override
    public int getItemCount() {
        return detailList.size();
    }

    public interface OnItemSelected {
        void onSelected(DataDetail detail);
    }

}
