package com.sound.prankparty.ThirdFragment;

import android.content.Context;
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.fragment.app.Fragment;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.sound.prankparty.Application.MainApplication;
import com.sound.prankparty.R;
import com.sound.prankparty.Room.FavoriteSounds;
import com.sound.prankparty.Utils.FavoriteSoundsDiffCallback;

import java.util.ArrayList;
import java.util.List;

public class FavoriteRecyclerViewAdapter extends RecyclerView.Adapter<FavoriteRecyclerViewAdapter.FavoriteRecyclerViewHolder> {

    private List<FavoriteSounds> favoriteSoundsList = new ArrayList<>();
    private Context context;
    private Fragment fragment;

    public FavoriteRecyclerViewAdapter(Context context, Fragment fragment) {
        this.context = context;
        this.fragment = fragment;
    }

    public void updateData(List<FavoriteSounds> newFavoriteSoundsList) {
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new FavoriteSoundsDiffCallback(favoriteSoundsList, newFavoriteSoundsList));
        favoriteSoundsList.clear();
        favoriteSoundsList.addAll(newFavoriteSoundsList);
        diffResult.dispatchUpdatesTo(this);
    }

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

    @Override
    public void onBindViewHolder(@NonNull FavoriteRecyclerViewHolder holder, int position) {
        FavoriteSounds favoriteSounds = favoriteSoundsList.get(position);
        holder.textView.setText(favoriteSounds.getName());

        Glide.with(MainApplication.getContext())
                .asDrawable()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(favoriteSounds.getImagePath())
                .transform(new CenterCrop())
                .into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        return favoriteSoundsList != null ? favoriteSoundsList.size() : 0;
    }

    static class FavoriteRecyclerViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        public FavoriteRecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.item_imageview_favorite);
            textView = itemView.findViewById(R.id.item_imageview_text);
        }
    }
}

