package com.example.quiz.data.adapter;

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

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

import com.example.quiz.R;
import com.example.quiz.data.model.dtos.auth.User;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AgentItemAdapter extends RecyclerView.Adapter<AgentItemAdapter.AgentItemViewHolder> {
    private List<User> agents = new ArrayList<>();
    public AgentItemAdapter(){

    }
    public AgentItemAdapter(List<User> agents) {
        this.agents = agents;
    }

    public interface onItemClickListener{
        void onItemClick(User agent);
    }

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


     static class AgentItemViewHolder extends  RecyclerView.ViewHolder{
      TextView txtCode, txtDate, txtAdresse;
      ImageButton details;
        public AgentItemViewHolder(@NonNull View itemView) {
            super(itemView);
            txtCode = itemView.findViewById(R.id.txtCode);
            txtDate = itemView.findViewById(R.id.txtDate);
            txtAdresse = itemView.findViewById(R.id.txtAdresse);
            details = itemView.findViewById(R.id.details);
        }

    }

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

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

    @Override
    public void onBindViewHolder(@NonNull AgentItemViewHolder holder, int position) {
        User agent = agents.get(position);
        holder.txtCode.setText(agent.getCode());
        if(agent.getDateEmbauche() == null){
            holder.txtDate.setText("Pas de date");
        }else{
            LocalDate date = LocalDate.parse(agent.getDateEmbauche());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            holder.txtDate.setText(dateTimeFormatter.format(date));
        }
        if(agent.getVille() == null || agent.getAdresse() == null){
            holder.txtAdresse.setText("Pas d'adresse");
        }else{
            String address = agent.getVille()+"; "+agent.getAdresse();
            holder.txtAdresse.setText(address);
        }
        holder.details.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(listener != null){
                    listener.onItemClick(agent);
                }
            }
        });
    }


}
