package it.integry.integrywmsnative;

import android.app.Application;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.Log;

import javax.inject.Inject;

import it.integry.integrywmsnative.core.context.AppContext;
import it.integry.integrywmsnative.core.data_store.db.RoomModule;
import it.integry.integrywmsnative.core.utility.UtilityLogger;


public class MainApplication extends Application {

    public static Resources res;

    // Reference to the application graph that is used across the whole app
    public static MainApplicationComponent appComponent;
    public static MainApplicationModule appModule;
    public static RoomModule roomModule;

    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    @Inject
    AppContext appContext;



    // Called when the application is starting, before any other application objects have been created.
    // Overriding this method is totally optional!
    @Override
    public void onCreate() {
        super.onCreate();

        appModule = new MainApplicationModule(this);
        roomModule = new RoomModule(this);
        appComponent = DaggerMainApplicationComponent.builder()
                .mainApplicationModule(appModule)
                .roomModule(roomModule)
                .build();

        appComponent.inject(this);

        res = getResources();

        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }

    // Called by the system when the device configuration changes while your component is running.
    // Overriding this method is totally optional!
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // This is called when the overall system is running low on memory,
    // and would like actively running processes to tighten their belts.
    // Overriding this method is totally optional!
    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    public static void exit() {
        System.exit(0);
    }


    // handler listener
    private final Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
            new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread thread, Throwable ex) {
                    // re-throw critical exception further to the os (important)
                    defaultUncaughtExceptionHandler.uncaughtException(thread, ex);

                    try {
                        UtilityLogger.error(new Exception(ex));
                        MainApplication.exit();
                    } catch (Exception e) {
                        Log.e("Uncaught error", "Exception Logger failed!", e);
                    }
                }
            };

}
