package com.sketch.papertracingart.Category;

import android.app.Activity;
import android.content.Intent;
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.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.sketch.papertracingart.Camera.CameraActivity;
import com.sketch.papertracingart.R;
import com.sketch.papertracingart.Room.AppDatabase;
import com.sketch.papertracingart.Room.FavoriteImage;
import com.sketch.papertracingart.Room.FavoriteImageDao;

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

public class ImageRecyclerViewAdapter extends RecyclerView.Adapter<ImageRecyclerViewAdapter.ViewHolder> {
    private List<String> imagePaths;

    private final FavoriteImageDao favoriteImageDao;
    private final Activity context;

    public ImageRecyclerViewAdapter(List<String> imagePaths, Activity context) {
        this.imagePaths = imagePaths;
        this.context = context;
        AppDatabase db = AppDatabase.getInstance(context);
        this.favoriteImageDao = db.favoriteImageDao();
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String imagePath = imagePaths.get(position);

        RequestOptions requestOptions = new RequestOptions()
                .transform(new CenterCrop(), new RoundedCorners(20)); // 20 是圆角半径

        if (imagePath.startsWith("/data/user/")) {
            Glide.with(context)
                    .load(imagePath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .apply(requestOptions)
                    .into(holder.imageView);
        } else {
            Glide.with(context)
                    .load("file:///android_asset/" + imagePath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .apply(requestOptions)
                    .into(holder.imageView);
        }
        Executors.newSingleThreadExecutor().execute(() -> {
            final boolean[] isFavorite = {checkFavoriteStatus(imagePath)};
            // 更新 UI 需要在主线程中执行
            context.runOnUiThread(() -> {
                updateFavoriteIcon(holder, isFavorite[0]);
                holder.favoriteButton.setOnClickListener(v -> {
                    isFavorite[0] = !isFavorite[0];
                    updateFavoriteIcon(holder, isFavorite[0]);
                    updateDatabase(imagePath, isFavorite[0]);
                });
            });
        });

        holder.imageView.setOnClickListener(v -> {
            Intent intent = new Intent(context, CameraActivity.class);
            intent.putExtra("imagePath", imagePath);
            context.startActivity(intent);
        });
    }

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

    private boolean checkFavoriteStatus(String imagePath) {
        FavoriteImage favoriteImage = favoriteImageDao.getByImagePath(imagePath);
        return favoriteImage != null;
    }

    private void updateDatabase(String imagePath, boolean isFavorite) {
        Executors.newSingleThreadExecutor().execute(() -> {
            FavoriteImage favoriteImage = new FavoriteImage(true, imagePath);
            if (isFavorite) {
                favoriteImageDao.insert(favoriteImage);
            } else {
                favoriteImageDao.deleteByImagePath(imagePath);
            }
        });
    }

    private void updateFavoriteIcon(ViewHolder holder, boolean isFavorite) {
        holder.favoriteButton.setImageResource(isFavorite ? R.drawable.favorite : R.drawable.unfavorite);
    }

    // 更新数据并使用 DiffUtil
    public void updateImagePaths(List<String> newImagePaths) {

        imagePaths = newImagePaths;

        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        ImageView favoriteButton;

        ViewHolder(View view) {
            super(view);
            imageView = view.findViewById(R.id.image_view);
            favoriteButton = view.findViewById(R.id.btn_favorite);
        }
    }

}
