package it.integry.integrywmsnative.core.context;

import android.content.Context;

import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;

import javax.inject.Inject;
import javax.inject.Singleton;

import it.integry.integrywmsnative.BuildConfig;
import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.core.data_store.db.AppDatabase;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.settings.Stash;
import it.integry.integrywmsnative.core.utility.UtilityContext;
import it.integry.integrywmsnative.core.utility.UtilityResources;
import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.core.utility.UtilityToast;

@Singleton
public class AppContext {

    //Note: this is the Application Context NOT the Activity Context
    private final Context mApplicationContext;

    @Inject
    AppDatabase mAppDatabase;

    public AppContext(Context context) {
        this.mApplicationContext = context;

        MainApplication.appComponent
                .inject(this);
    }




    @Inject
    public void init() {
        this.initUtilities();

        this.initSettings();

        this.initCrashlytics();

        this.initLogger();
    }



    private void initSettings() {
        Stash.init(mApplicationContext);
        SettingsManager.init(mApplicationContext);
    }

    private void initCrashlytics() {
        if(!BuildConfig.DEBUG) {
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();

            if(     SettingsManager.isInstanceAvailable() &&
                    (SettingsManager.i().getUserSession() != null && !UtilityString.isNullOrEmpty(SettingsManager.i().getUserSession().getProfileDB())) &&
                    (SettingsManager.i().getUser() != null && !UtilityString.isNullOrEmpty(SettingsManager.i().getUser().getFullname()))) {

                crashlytics.setUserId(SettingsManager.i().getUser().getFullname());
                crashlytics.setCustomKey("profile_db", SettingsManager.i().getUserSession().getProfileDB());
            }
        }
    }

    private void initUtilities() {
        UtilityContext.initApplicationContext(mApplicationContext);
        UtilityResources.init(mApplicationContext);
        UtilityToast.init(mApplicationContext);
    }

    private void initLogger() {
        Logger.addLogAdapter(new AndroidLogAdapter());
    }


}
