package com.example.vdcscore.ui.clubs;

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

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

import com.bumptech.glide.Glide;

import com.example.vdcscore.R;
import com.example.vdcscore.models.Player;

import java.util.List;

public class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerViewHolder> {

    private final List<Player> mPlayers;
    private final OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(Player player);
    }

    public PlayerAdapter(List<Player> players, OnItemClickListener listener) {
        this.mPlayers = players;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull PlayerViewHolder holder, int position) {
        Player player = mPlayers.get(position);
        holder.bind(player, listener);
    }

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

    static class PlayerViewHolder extends RecyclerView.ViewHolder {
        private final TextView name;
        private final ImageView photo;

        public PlayerViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.text_player_name);
            photo = itemView.findViewById(R.id.image_player_icon);
        }

        public void bind(Player player, OnItemClickListener listener) {
            if (player != null) {
                name.setText(player.getNome());

                if (player.getFoto() != null && !player.getFoto().isEmpty()) {
                    Glide.with(itemView.getContext())
                            .load(player.getFoto())
                            .circleCrop()
                            .placeholder(R.drawable.ic_menu_camera)
                            .error(R.drawable.ic_menu_camera)
                            .into(photo);
                } else {
                    photo.setImageResource(R.drawable.ic_menu_camera);
                }

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