package com.ardrawing.ardrawingspace.util;

import android.app.Application;
import android.content.res.AssetManager;
import android.util.Log;

import com.ardrawing.ardrawingspace.room.SpaceEntity;

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

public class FileParsingAndInitialization {
    private final Application application;
    private static final String IMAGE_PREFIX = "png_";
    private static final String IMAGE_EXTENSION = ".jpg";

    public FileParsingAndInitialization(Application application) {
        this.application = application;
    }

    public void insertImagesToDatabase() {
        AssetManager assetManager = application.getAssets();
        try {
            String[] directories = assetManager.list("");
            if (directories == null) {
                Log.w("InitDatabase", "No directories found in assets");
                return;
            }

            for (String dir : directories) {
                if (!dir.startsWith(IMAGE_PREFIX)) continue;
                importImagesFromDirectory(dir);
            }
        } catch (IOException e) {
            Log.e("InitDatabase", "Failed to list asset directories", e);
        }
    }

    private void importImagesFromDirectory(String directory) {
        AssetManager assetManager = application.getAssets();
        try {
            String[] files = assetManager.list(directory);
            if (files == null) {
                Log.w("InitDatabase", "No files found in directory: " + directory);
                return;
            }

            List<SpaceEntity> imageList = new ArrayList<>();
            for (String file : files) {
                if (file.endsWith(IMAGE_EXTENSION)) {
                    String imagePath = directory + "/" + file;
                    imageList.add(new SpaceEntity(imagePath, false, false));
                }
            }

            if (!imageList.isEmpty()) {
                insertImagesAsync(imageList);
            }
        } catch (IOException e) {
            Log.e("InitDatabase", "Failed to list files in directory: " + directory, e);
        }
    }

    private void insertImagesAsync(List<SpaceEntity> imageList) {
        new Thread(() -> {
            SpaceRepository repository = new SpaceRepository(application);
            repository.insertAll(imageList);
        }).start();
    }
}