package com.ardraw.ardrawingflow.util;

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

import com.ardraw.ardrawingflow.data.database.dao.FlowDataDao;
import com.ardraw.ardrawingflow.data.database.AppDatabase;
import com.ardraw.ardrawingflow.data.database.entity.FlowData;
import com.ardraw.ardrawingflow.data.repository.FlowRepository;

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

public class InitDatabase {
    private final Context context;

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

    public void insertImagesToDatabase() {
        AssetManager assetManager = context.getAssets();
        try {
            String[] directories = assetManager.list("");
            if (directories != null) {
                for (String dir : directories) {
                    if (!dir.startsWith("png_")) continue;
                    importImagesFromDirectory(dir);
                }
            }
        } catch (IOException ignored) {
        }
    }

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

                insertImagesToDatabase(imageList);
            }
        } catch (IOException ignored) {
        }
    }

    private void insertImagesToDatabase(List<FlowData> imageList) {
        FlowDataDao flowDataDao = AppDatabase.getInstance(context).flowDataDao();
        FlowRepository databaseUtil = new FlowRepository(flowDataDao);
        databaseUtil.insertAll(imageList);
    }
}

