package com.ardraw.ardrawingflow;

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

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.applovin.sdk.AppLovinMediationProvider;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkConfiguration;
import com.applovin.sdk.AppLovinSdkInitializationConfiguration;
import com.ardraw.ardrawingflow.util.InitDatabase;
import com.google.firebase.FirebaseApp;

public class MyApplication extends Application {
    public static MyApplication application;
    public static final String DATABASE_NAME = "Room";
    public static final int DATABASE_VERSION = 1;
    private static final String PREF_NAME = "preferences";
    private static final String KEY_INITIALIZED = "initRoom";

    public static final String TAG = "--------------";

    public static final String AD_BROADCAST = "on_success_action";
    private static final String MAX_SDK = "os4_cxdNCbSNNKBlfTkCd_TVBRkGvcT12MSpwSAyNcOXbqSpEdv0QrmmzC0mh4C_fBhKypHEWPW3Cr5JLSobVL";
    public static Boolean initSDK = false;

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

        application = this;

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

        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() {

        AppLovinSdkInitializationConfiguration initConfig = AppLovinSdkInitializationConfiguration.builder(MAX_SDK, this)
                .setMediationProvider(AppLovinMediationProvider.MAX)
                .build();
        AppLovinSdk.getInstance(this).initialize(initConfig, new AppLovinSdk.SdkInitializationListener() {
            @Override
            public void onSdkInitialized(final AppLovinSdkConfiguration sdkConfig) {
                initSDK = true;
                LocalBroadcastManager.getInstance(getContext()).sendBroadcast(new Intent(AD_BROADCAST));
            }
        });
        AppLovinSdk.getInstance(this).getSettings().setVerboseLogging(true);
        //MAX广告测试
//        AppLovinSdk.getInstance( this ).showMediationDebugger();

    }

    private void initDatabase() {
        InitDatabase initDatabase = new InitDatabase(getContext());
        initDatabase.insertImagesToDatabase();
    }

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