package com.wallpaper.wallpaperbox;

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

import com.wallpaper.wallpaperbox.data.dao.WallpaperEntityDao;
import com.wallpaper.wallpaperbox.data.database.AppDatabase;
import com.wallpaper.wallpaperbox.data.entity.WallpaperEntity;
import com.wallpaper.wallpaperbox.data.repository.WallpaperRepository;
import com.wallpaper.wallpaperbox.util.JsonUtil;

import java.util.List;

public class MyApplication extends Application {

    public static MyApplication application;
    public static final int DB_VERSION = 1;
    public static final String DB_NAME = "wallpaper_database";
    private static final String PREF_NAME = "app_preferences";
    private static final String KEY_INITIALIZED = "isInit";

    @Override
    public void onCreate() {
        super.onCreate();

        application = this;

        SharedPreferences preferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        boolean isDatabaseInitialized = preferences.getBoolean(KEY_INITIALIZED, false);

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

    public static Context getContext() {
        return application.getApplicationContext();
    }

    private void initializeDatabase() {
        WallpaperEntityDao wallpaperEntityDao = AppDatabase.getInstance(getContext()).wallpaperEntityDao();
        WallpaperRepository wallpaperRepository = new WallpaperRepository(wallpaperEntityDao);
        List<WallpaperEntity> wallpaperEntities = JsonUtil.parseJson(getContext(), "wallpaper.json");
        wallpaperRepository.insertAll(wallpaperEntities);
    }
}
