package com.cake.draw.painting.adapter;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.cake.draw.painting.databinding.ItemHomeImageCakeBinding;
import com.cake.draw.painting.tools.Utils;
import com.cake.draw.painting.onClickListener;
import java.util.List;

public class HomeCakeAdapter extends RecyclerView.Adapter<HomeCakeAdapter.ViewHolder> {
    private Context context;
    private List<String> imagePathList; // 唯一图片路径列表（删除data变量）
    private String currentCategoryDir;
    private onClickListener listener;

    public void setData(List<String> newImagePathList) {
        this.imagePathList = newImagePathList;
        notifyDataSetChanged(); // 刷新列表
    }

    public HomeCakeAdapter(Context context) {
        this.context = context;
    }

    // 设置item点击监听
    public void setListener(onClickListener listener) {
        this.listener = listener;
    }

    // 核心：刷新分类图片数据
    public void refreshData(List<String> newImagePathList, String categoryDir) {
        this.imagePathList = newImagePathList;
        this.currentCategoryDir = categoryDir;
        notifyDataSetChanged(); // 刷新列表
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载图片item布局（见第三步）
        ItemHomeImageCakeBinding binding = ItemHomeImageCakeBinding.inflate(
                LayoutInflater.from(context), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String imageAssetPath = imagePathList.get(position);
        // 从Assets加载图片（调用Utils的loadImageFromAssets方法）
        holder.binding.ivImage.setImageBitmap(Utils.loadImageFromAssets(context, imageAssetPath));

        // 图片点击事件（可跳转Camera/PreView）
        holder.binding.ivImage.setOnClickListener(v -> {
            if (listener != null) {
                listener.onClickItem(false, imageAssetPath);
            }
        });
    }

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

    // ViewHolder：绑定图片item布局
    public static class ViewHolder extends RecyclerView.ViewHolder {
        ItemHomeImageCakeBinding binding;

        public ViewHolder(ItemHomeImageCakeBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}