package it.integry.integrywmsnative.core.exception;

import android.app.Activity;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import it.integry.integrywmsnative.BuildConfig;
import it.integry.integrywmsnative.core.utility.UtilityLogger;
import it.integry.integrywmsnative.view.dialogs.exception.DialogException;

public class ExceptionsHandler implements Thread.UncaughtExceptionHandler {

    private final static String TAG = ExceptionsHandler.class.getSimpleName();

    private final Activity context;

    public static void init(Activity context) {
        new ExceptionsHandler(context);
    }

    private ExceptionsHandler(Activity context) {
        this.context = context;

        //if (!BuildConfig.DEBUG) {
            Thread.setDefaultUncaughtExceptionHandler(this);


        //}

    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        try {
            UtilityLogger.errorMe(new Exception(ex));
        } catch (Exception e) {
            Log.e(TAG, "Exception Logger failed!", e);
            System.exit(0);
        }

        appendToFile(new Exception(ex));
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                DialogException.make(context, context::finish).show();
                Looper.loop();
            }
        }.start();



    }

    public void appendToFile(Exception e) {
        try {
            File yourFile = new File(Environment.getExternalStorageDirectory(), "log.txt");

            FileWriter fstream = new FileWriter(yourFile.getPath(), true);
            BufferedWriter out = new BufferedWriter(fstream);
            PrintWriter pWriter = new PrintWriter(out, true);
            e.printStackTrace(pWriter);
        }
        catch (Exception ie) {
            throw new RuntimeException("Could not write Exception to file", ie);
        }
    }
}