package com.example.lab1;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

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

import java.util.List;

public class GradeAdapter extends RecyclerView.Adapter<GradeAdapter.GradeViewHolder> {
    public static class GradeViewHolder extends RecyclerView.ViewHolder {
        TextView tvSubject;
        RadioGroup rgGrade;

        GradeViewHolder(@NonNull View itemView) {
            super(itemView);
            tvSubject = itemView.findViewById(R.id.tvSubject);
            rgGrade = itemView.findViewById(R.id.rgGrade);
        }
    }

    private final List<Subject> subjects;
    private final int[] gradeOptions = {2,3,4,5};

    public GradeAdapter(List<Subject> subjects) {
        this.subjects = subjects;
    }

    @NonNull
    @Override
    public GradeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.grades_row, parent, false);
        return new GradeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull GradeViewHolder holder, int position) {
        Subject item = subjects.get(position);
        holder.tvSubject.setText(item.name);
        holder.rgGrade.removeAllViews();

        for (double grade : gradeOptions) {
            RadioButton rb = new RadioButton(holder.itemView.getContext());
            rb.setText(String.valueOf(grade));
            rb.setId(View.generateViewId());
            rb.setTag(grade);

            rb.setChecked(item.grade == grade);

            holder.rgGrade.addView(rb);
        }

        holder.rgGrade.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton selected = group.findViewById(checkedId);
            if (selected != null) {
                item.grade = (double)selected.getTag();
            }
        });
    }

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

    public List<Subject> getGradeItems() {
        return subjects;
    }
}
