package com.ar.paintar.utils;

import android.content.Context;

import androidx.lifecycle.LiveData;

import com.ar.paintar.MyApplication;
import com.ar.paintar.room.AppDatabase;
import com.ar.paintar.room.ImageData;
import com.ar.paintar.room.ImageDataDao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseUtil {

    private final ImageDataDao imageDataDao;

    public DatabaseUtil(Context context) {
        AppDatabase db = AppDatabase.getInstance(context);
        imageDataDao = db.imageDataDao();
    }

    public void insertAllImages(List<String> imagePaths) {
        List<ImageData> imageEntries = new ArrayList<>();
        for (String path : imagePaths) {
            imageEntries.add(new ImageData(false, false, path));
        }

        imageDataDao.insertAll(imageEntries);
    }

    public List<String> getAllImagePathsFromAssets() {
        List<String> imagePaths = new ArrayList<>();
        try {
            String[] categories = MyApplication.getContext().getAssets().list("");
            if (categories != null) {
                for (String category : categories) {
                    if (category.startsWith("png_")) {
                        String[] files = MyApplication.getContext().getAssets().list(category);
                        if (files != null) {
                            for (String file : files) {
                                imagePaths.add(category + "/" + file);
                            }
                        }
                    }
                }
            }
        } catch (IOException ignored) {
        }
        return imagePaths;
    }

    public LiveData<List<ImageData>> getAllFavoriteImageData() {
        return imageDataDao.getLiveAllFavoriteImageData();
    }

    public List<ImageData> getAllImportImageData() {
        return imageDataDao.getAllImportImageData();
    }

    public void insertImageData(ImageData imageData) {
        imageDataDao.insert(imageData);
    }

    public LiveData<List<ImageData>> getFirstCategory(String category) {
        return imageDataDao.getLiveFirstImageDataByCategory(category);
    }

    public LiveData<List<ImageData>> getLiveAllCategory(String category) {
        return imageDataDao.getLiveAllImageDataByCategory(category);
    }

}
