package com.ardraw.ardrawinggallery.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.ardraw.ardrawinggallery.room.ArData;

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

public class ArDataInsert {
    private final Context context;

    public ArDataInsert(Context context) {
        this.context = context;
    }

    public void insertImagesToDatabase() {
        AssetManager assetManager = context.getAssets();
        try {
            String[] directories = assetManager.list("");
            Log.d("ImageDataImporter", "Loading asset directories" + Arrays.toString(directories));
            if (directories != null) {
                for (String dir : directories) {
                    Log.d("ImageDataImporter", "Importing images from directory: " + dir);
                    if (!dir.startsWith("png_")) continue;
                    importImagesFromDirectory(dir);
                    Log.d("ImageDataImporter", "Imported images from directory: " + dir);
                }
                Log.d("ImageDataImporter", "All images imported");
            }
        } catch (IOException e) {
            Log.e("ImageDataImporter", "Error loading asset directories", e);
        }
    }

    private void importImagesFromDirectory(String directory) {
        AssetManager assetManager = context.getAssets();
        try {
            String[] files = assetManager.list(directory);
            Log.d("ImageDataImporter", "Importing images from directory: " + directory);
            if (files != null) {
                List<ArData> imageList = new ArrayList<>();
                for (String file : files) {
                    if (file.endsWith(".jpg")) {
                        String imagePath = directory + "/" + file;
                        imageList.add(new ArData(imagePath, false, false));
                        Log.d("ImageDataImporter", "Imported image: " + imagePath);
                    }
                }

                insertImagesToDatabase(imageList);
            }
        } catch (IOException e) {
            Log.e("ImageDataImporter", "Error loading files from directory: " + directory, e);
        }
    }

    private void insertImagesToDatabase(List<ArData> imageList) {
        DatabaseUtil databaseUtil = new DatabaseUtil(context);
        databaseUtil.insertAll(imageList);
    }
}

