package com.lock.arcanvasart;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.lock.arcanvasart.Utils.ImageRepository;

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

public class MyApplication extends Application {

    private static Context mContext;
    public static final int DB_Version = 1;
    public static final String DB_Name = "image_database";
    private static final String PREF_NAME = "app_preferences";
    private static final String KEY_INITIALIZED = "isDatabaseInitialized";

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();

        // 检查是否需要初始化数据库
        SharedPreferences preferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        boolean isDatabaseInitialized = preferences.getBoolean(KEY_INITIALIZED, false);

        if (!isDatabaseInitialized) {
            initializeDatabase();
            preferences.edit().putBoolean(KEY_INITIALIZED, true).apply();
        }
    }

    private void initializeDatabase() {
        Executors.newSingleThreadExecutor().execute(() -> {
            List<String> imagePaths = getAllImagePathsFromAssets();
            ImageRepository imageRepository = new ImageRepository(mContext);
            imageRepository.insertAllImages(imagePaths);
        });
    }

    private List<String> getAllImagePathsFromAssets() {
        List<String> imagePaths = new ArrayList<>();
        try {
            // 获取 assets 目录下的所有类别
            String[] categories = mContext.getAssets().list("");  // 获取 assets 根目录下的所有文件夹
            if (categories != null) {
                // 遍历所有类别
                for (String category : categories) {
                    if (category.startsWith("png_")) {  // 只处理类别，假设类别前缀为 "png_"
                        // 获取指定类别下的所有图片文件
                        String[] files = mContext.getAssets().list(category);
                        if (files != null) {
                            // 将每个文件路径加到列表中
                            for (String file : files) {
                                imagePaths.add(category + "/" + file); // 更新为完整路径
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            Log.e("MyApplication", "Error loading images from assets", e);
        }
        return imagePaths;
    }


    public static Context getContext() {
        return mContext;
    }
}
