package com.lock.arcanvasart.Utils;

import android.content.Context;

import androidx.lifecycle.LiveData;

import com.lock.arcanvasart.MyApplication;
import com.lock.arcanvasart.room.AppDatabase;
import com.lock.arcanvasart.room.FavoriteImage;
import com.lock.arcanvasart.room.FavoriteImageDao;

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

public class ImageRepository {

    private final FavoriteImageDao favoriteImageDao;

    public ImageRepository(Context context) {
        // 初始化数据库
        AppDatabase db = AppDatabase.getInstance(context);
        favoriteImageDao = db.favoriteImageDao();
    }

    // 批量插入图片路径
    public void insertAllImages(List<String> imagePaths) {
        // 将图片路径转化为 FavoriteImage 实体，isFavorite 默认为 false
        List<FavoriteImage> images = new ArrayList<>();
        for (String path : imagePaths) {
            images.add(new FavoriteImage(path, false));  // 初始化时 isFavorite 为 false
        }

        // 执行插入操作
        favoriteImageDao.insertAll(images);
    }

    public LiveData<List<FavoriteImage>> getAllFavoriteImages() {
        return favoriteImageDao.getAllFavoriteImages();
    }

    public void updateFavoriteStatus(FavoriteImage favoriteImage) {
        new Thread(() -> {
            AppDatabase db = AppDatabase.getInstance(MyApplication.getContext());
            db.favoriteImageDao().update(favoriteImage);  // 更新数据库中的收藏状态
        }).start();
    }

    public LiveData<FavoriteImage> getImageByPath(String path) {
        return favoriteImageDao.getImageByPath(path);  // 查询数据库中是否存在该路径的记录
    }


}
