package com.artisanic.helper.artadapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.artisanic.helper.artui.ArtCameraActivity;
import com.artisanic.helper.ArtApp; // 确保导入该类
import com.artisanic.helper.test.databinding.ItemSearchImageBinding;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

    private final Context mContext;
    private List<String> mImagePathList;

    public SearchAdapter(Context context, List<String> imagePathList) {
        this.mContext = context;
        this.mImagePathList = imagePathList;
    }

    public void updateData(List<String> newList) {
        this.mImagePathList = newList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemSearchImageBinding binding = ItemSearchImageBinding.inflate(
                LayoutInflater.from(mContext), parent, false);
        return new ImageViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        String imagePath = mImagePathList.get(position);
        try (InputStream is = mContext.getAssets().open(imagePath)) {
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            holder.binding.ivImage.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        holder.binding.ivImage.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, ArtCameraActivity.class);
            intent.putExtra(ArtApp.Key_Camera, imagePath);
            mContext.startActivity(intent);
        });
    }

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

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        private final ItemSearchImageBinding binding;

        public ImageViewHolder(ItemSearchImageBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }
}