package com.apps.chillscreen.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

import com.apps.chillscreen.R;
import com.apps.chillscreen.bean.Picture;
import com.apps.chillscreen.databinding.ItemGirdBinding;
import com.apps.chillscreen.listener.CardClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

public class GirdAdapter extends RecyclerView.Adapter<GirdAdapter.GirdViewHolder> {
    private Context context;
    private List<Picture> pictureList;
    private CardClickListener cardClickListener;

    @NonNull
    @Override
    public GirdViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();
        ItemGirdBinding inflate = ItemGirdBinding.inflate(LayoutInflater.from(context), parent, false);
        return new GirdViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull GirdViewHolder holder, int position) {
        Picture picture = pictureList.get(position);
        String preViewUrl400 = picture.getPreviewUrl400();
        Glide.with(context).asDrawable()
                .skipMemoryCache(true)
                .apply(new RequestOptions().format(DecodeFormat.PREFER_RGB_565))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(preViewUrl400)
                .error(R.mipmap.img_placeholder)
                .placeholder(R.mipmap.img_placeholder)
                .into(holder.binding.img);
        holder.binding.layout.setOnClickListener(v -> cardClickListener.onDetailClick(picture) );
    }

    @Override
    public int getItemCount() {
        Log.d("YYYYYY","pictureList.size is"+pictureList.size());
        return pictureList.size();
    }

    public void setPictureList(List<Picture> pictures) {
        this.pictureList = pictures;
        notifyDataSetChanged();
    }

    public void setClickListener(CardClickListener listener){
        this.cardClickListener=listener;
    }

    static class GirdViewHolder extends RecyclerView.ViewHolder {
        ItemGirdBinding binding;

        public GirdViewHolder(@NonNull ItemGirdBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }
}
