package com.ElyStudio.leGaou.adapter;

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

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

import com.google.android.material.card.MaterialCardView;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.models.Avatars;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.OnItemClick;
import com.squareup.picasso.Picasso;

import java.util.List;

public class AvatarAdapter extends RecyclerView.Adapter<AvatarAdapter.AvatarViewHolder> {

    private final List<Avatars> avatarsList;
    int selectedIndex = 0 ;
    private final OnItemClick mCallBack;

    public AvatarAdapter(List<Avatars> avatarsList, OnItemClick mCallBack) {
        this.avatarsList = avatarsList;
        this.mCallBack = mCallBack;
    }

    @NonNull
    @Override
    public AvatarAdapter.AvatarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new AvatarViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.avatar_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull AvatarAdapter.AvatarViewHolder holder, int position) {
        String avatarImage = avatarsList.get(position).getImage();
        if(holder.getAdapterPosition() == selectedIndex)
        {
            mCallBack.onClick(avatarImage);
            holder.avatarCard.setStrokeWidth(8);
        }
        else
        {
            holder.avatarCard.setStrokeWidth(0);
        }
        if(avatarImage != null && !avatarImage.equals(""))
        {
            Picasso.get().load(Constants.ADMIN_PANEL_URL +avatarImage).into(holder.avatarImage);
        }

        holder.avatarCard.setOnClickListener(v -> {
            selectedIndex = holder.getAdapterPosition();
            mCallBack.onClick(avatarImage);
            notifyDataSetChanged();
        });
    }

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

    public static class AvatarViewHolder extends RecyclerView.ViewHolder {
        MaterialCardView avatarCard;
        ImageView avatarImage;
        public AvatarViewHolder(@NonNull View itemView) {
            super(itemView);

            avatarCard = itemView.findViewById(R.id.avatarCard);
            avatarImage = itemView.findViewById(R.id.avatarImage);

        }
    }
}