package com.ar.paintar;

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

import com.anythink.core.api.ATSDK;
import com.anythink.core.api.NetTrafficeCallback;
import com.ar.paintar.topon.AdManager;
import com.ar.paintar.utils.DatabaseUtil;

import java.util.List;
import java.util.concurrent.Executors;

public class MyApplication extends Application {

    private static MyApplication instance;

    public static final int Db_Version = 1;
    public static final String Db_Name = "image_database";

    private static final String PREF_NAME = "preferences";
    private static final String KEY_INITIALIZED = "init";

    public static final String TAG = "--------------";
    private static final String AppKey = "a586013b343d14d3a9fb40b12a3a3deb5";
    private static final String APPId = "h67594cd4131a4";
    private static final String debug_KEy = "fe06c76b794f95216f98e5982ae8f335fc558956";

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

        instance = this;

//        //确保Firebase初始化
//        FirebaseApp.initializeApp(this);
//
//        // 输出日志以确认Firebase初始化
//        if (!FirebaseApp.getApps(this).isEmpty()) {
//            Log.d(TAG, "Firebase 初始化成功");
//        } else {
//            Log.e(TAG, "Firebase 初始化失败");
//        }
        initSdk();

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

        if (!init) {
            initDatabase();
            preferences.edit().putBoolean(KEY_INITIALIZED, true).apply();
        }

    }

    private void initSdk() {

        ATSDK.checkIsEuTraffic(this, new NetTrafficeCallback() {

            @Override
            public void onResultCallback(boolean isEU) {
                Log.e(TAG, "onResultCallback:" + isEU);
                if (isEU && ATSDK.getGDPRDataLevel(MyApplication.this) == ATSDK.UNKNOWN) {
                    ATSDK.showGdprAuth(MyApplication.this);
                }

            }

            @Override
            public void onErrorCallback(String errorMsg) {
                Log.e(TAG, "onErrorCallback:" + errorMsg);
            }
        });

        ATSDK.init( this, APPId, AppKey);
        AdManager.loadAllAd();
        //测试工具
//        ATDebuggerUITest.showDebuggerUI(this,debug_KEy);
//        ATSDK.setNetworkLogDebug(true);

    }


    private void initDatabase() {
        Executors.newSingleThreadExecutor().execute(() -> {
            DatabaseUtil databaseUtil = new DatabaseUtil(getContext());
            List<String> imagePaths = databaseUtil.getAllImagePathsFromAssets();
            databaseUtil.insertAllImages(imagePaths);
        });
    }

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

}

