package com.example.quiz.data.adapter;


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

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

import com.example.quiz.R;
import com.example.quiz.data.model.Course;
import com.example.quiz.viewModel.SharedViewModel;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class BetsAdapter extends RecyclerView.Adapter<BetsAdapter.BetViewHolder> {

    private List<Course> bets = new ArrayList<>();
    private onItemClickListener listener;
    private SharedViewModel shared;

    public BetsAdapter(SharedViewModel shared) {
        this.shared = shared;
    }

    public interface onItemClickListener {
        void onItemClick(Course bet);
    }

    public void setOnItemClickListener(onItemClickListener listener){
        this.listener = listener;
    }

    public void setBets(List<Course> bets){
        this.bets = bets;
        notifyDataSetChanged();
    }

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

    @Override
    public void onBindViewHolder(@NonNull BetViewHolder holder, int position) {
        Course bet = bets.get(position);

        holder.tvDate.setText(LocalDateTime.parse(
                bet.getDateDepartCourse(),
                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
        ).format(
                DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
        ));
        holder.tvName.setText(bet.getNom());

        if (shared != null && shared.selectedReunion.getValue() != null) {
            holder.tvReunion.setText(shared.selectedReunion.getValue().getNom());
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) listener.onItemClick(bet);
        });
    }

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

    static class BetViewHolder extends RecyclerView.ViewHolder{
        TextView tvName, tvDate, tvReunion;

        public BetViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            tvDate = itemView.findViewById(R.id.tvDate);
            tvReunion = itemView.findViewById(R.id.tvReunion);
        }
    }
}
