package com.wall.engine.wallpaper;

import android.content.Context;
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.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;

public class K4ImageAdapter extends RecyclerView.Adapter<K4ImageAdapter.ImageViewHolder> {

    private final Context mContext;
    private final List<WallpaperItem> mWallpaperList;
    private OnItemClickListener mOnItemClickListener;

    private final RequestOptions glideOptions = new RequestOptions()
            .centerCrop()
            .placeholder(R.drawable.load_ing)
            .error(R.drawable.load_ing)
            .override(400, 600); // 统一缩略图尺寸（宽400，高600）

    public interface OnItemClickListener {
        void onItemClick(int position, WallpaperItem wallpaperItem);
    }

    public K4ImageAdapter(Context context, List<WallpaperItem> wallpaperList) {
        this.mContext = context;
        this.mWallpaperList = wallpaperList;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView ivItem4k;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            ivItem4k = itemView.findViewById(R.id.iv_item_4k);
        }
    }

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

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        WallpaperItem wallpaperItem = mWallpaperList.get(position);

        Glide.with(mContext)
                .load(wallpaperItem.getUrls().getSmall()) // 加载小图作为缩略图
                .apply(glideOptions) // 应用统一配置
                .into(holder.ivItem4k);

        holder.itemView.setOnClickListener(v -> {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(position, wallpaperItem);
            }
        });
    }

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