package com.lock.arcanvasart.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.lock.arcanvasart.R;
import com.lock.arcanvasart.activity.CameraActivity;
import com.lock.arcanvasart.room.AppDatabase;
import com.lock.arcanvasart.room.FavoriteImage;

import java.util.List;
import java.util.concurrent.Executors;

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

    private Context context;
    private List<FavoriteImage> images;

    public MainAdapter(Context context, List<FavoriteImage> imagePaths) {
        this.context = context;
        this.images = imagePaths;
    }

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

    @Override
    public void onBindViewHolder(ImageViewHolder holder, int position) {
        FavoriteImage image = images.get(position);
        holder.bind(image);
    }

    @Override
    public int getItemCount() {
        return images.size();
    }

    public class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView favorite;
        public ImageViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
            favorite = itemView.findViewById(R.id.btn_favorite);
        }

        void bind(FavoriteImage favoriteImage) {
            // 加载图片
            Glide.with(context)
                    .load("file:///android_asset/" + favoriteImage.getImagePath()) // 加载 assets 中的图片
                    .into(imageView);

            imageView.setOnClickListener(v -> {

                Intent intent = new Intent(context, CameraActivity.class);
                intent.putExtra("imagePath", favoriteImage.getImagePath());
                context.startActivity(intent);

            });

            // 设置收藏按钮状态
            favorite.setImageResource(favoriteImage.isFavorite() ? R.drawable.select_favorite : R.drawable.unselect_favorite);

            // 点击切换收藏状态
            favorite.setOnClickListener(v -> {
                boolean newStatus = !favoriteImage.isFavorite();
                favoriteImage.setFavorite(newStatus);

                // 在后台线程中执行数据库更新操作
                Executors.newSingleThreadExecutor().execute(() -> {
                    AppDatabase.getInstance(context)
                            .favoriteImageDao()
                            .update(favoriteImage); // 更新数据库状态
                });

                // 更新按钮图标
                notifyItemChanged(getAdapterPosition());
            });

        }

    }
}

