package be.iminds.ilabt.jfed.ui.commandline;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintStream;

/**
 * User: twalcari
 * Date: 6/25/2015
 * Time: 13:48
 */
public class UncaughtCliExceptionLogger implements Thread.UncaughtExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(UncaughtCliExceptionLogger.class);

    private final PrintStream err;

    private UncaughtCliExceptionLogger(final PrintStream err) {
        this.err = err;
    }
    private static UncaughtCliExceptionLogger instance;
    /* singleton, this way, it can optionally later be used by other parts of jFed to retrieve exception info. */
    public static UncaughtCliExceptionLogger getInstance(final PrintStream err) {
        if (instance == null) {
            instance = new UncaughtCliExceptionLogger(err);
        }
        return instance;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        LOG.error("UNCAUGHT ERROR IN THREAD {}", t.getName(), e);
        if (err != null) {
            err.println("UNCAUGHT ERROR IN THREAD "+t.getName());
            e.printStackTrace(err);
        }

        if (e instanceof OutOfMemoryError) {
            LOG.warn("jFed ran out of memory and will exit.");
            err.println("jFed ran out of memory and will exit.");
            System.exit(-1);
        }

        LOG.info("Will now exit due to uncaught exception.");
        if (err != null) {
            err.println("Will now exit due to uncaught exception.");
        }

        System.exit(-1);
    }
}
