package com.example.myapplication.Tool;

import android.content.Context;
import android.graphics.Color;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.example.myapplication.model.ImageInfo;

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

public class ImageAdapter extends BaseAdapter {
    private final Context context;
    private final List<ImageInfo> imageList;
    private final SparseBooleanArray selectedItems;

    public ImageAdapter(Context context, List<ImageInfo> imageList) {
        this.context = context;
        this.imageList = imageList;
        this.selectedItems = new SparseBooleanArray();
    }

    @Override
    public int getCount() {
        return imageList.size();
    }

    @Override
    public Object getItem(int position) {
        return imageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(5, 5, 5, 5);
        } else {
            imageView = (ImageView) convertView;
        }

        ImageInfo imageInfo = imageList.get(position);
        imageView.setImageBitmap(imageInfo.thumbnail);

        // 设置选中状态
        if (selectedItems.get(position, false)) {
            imageView.setBackgroundColor(Color.BLUE);
        } else {
            imageView.setBackgroundColor(Color.TRANSPARENT);
        }

        imageView.setOnClickListener(v -> {
            if (selectedItems.get(position, false)) {
                selectedItems.delete(position);
                imageView.setBackgroundColor(Color.TRANSPARENT);
            } else {
                selectedItems.put(position, true);
                imageView.setBackgroundColor(Color.BLUE);
            }
        });

        return imageView;
    }

    public List<ImageInfo> getSelectedImages() {
        List<ImageInfo> selected = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            if (selectedItems.get(i, false)) {
                selected.add(imageList.get(i));
            }
        }
        return selected;
    }
}
