package com.fireflysource.common.lifecycle;

import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class AbstractLifeCycle implements LifeCycle {

//    private static final List<Callback> stopActions = new CopyOnWriteArrayList<>();
//
//    static {
//        Runtime.getRuntime().addShutdownHook(new Thread(AbstractLifeCycle::stopAll, "the firefly shutdown thread"));
//    }

    protected AtomicBoolean start = new AtomicBoolean(false);
//    private final Callback stopCallback = this::stopNoRemove;

//    public AbstractLifeCycle() {
//        stopActions.add(stopCallback);
//    }

    @Override
    public boolean isStarted() {
        return start.get();
    }

    @Override
    public boolean isStopped() {
        return !start.get();
    }

    @Override
    public void start() {
        if (start.compareAndSet(false, true)) {
            init();
        }
    }

    @Override
    public void stop() {
        if (start.compareAndSet(true, false)) {
            try {
                destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            stopActions.remove(stopCallback);
        }
    }

    private void stopNoRemove() {
        if (start.compareAndSet(true, false)) {
            try {
                destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    abstract protected void init();

    abstract protected void destroy();

    public static void stopAll() {
//        if (!stopActions.isEmpty()) {
//            stopActions.forEach(a -> {
//                try {
//                    a.call();
//                } catch (Exception e) {
//                    System.err.println(e.getMessage());
//                }
//            });
//            System.out.println("Shutdown instance: " + stopActions.size());
//            stopActions.clear();
//        }

        ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
        if (iLoggerFactory instanceof Closeable) {
            try {
                ((Closeable) iLoggerFactory).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

@@ -1287,24 +1287,26 @@
    %7D%0A    %7D%0A%0A
+//
     private 
@@ -1323,24 +1323,26 @@
 oRemove() %7B%0A
+//
         if (
@@ -1369,32 +1369,34 @@
 true, false)) %7B%0A
+//
             try 
@@ -1389,32 +1389,34 @@
           try %7B%0A
+//
                 
@@ -1418,32 +1418,34 @@
      destroy();%0A
+//
             %7D ca
@@ -1456,32 +1456,34 @@
 (Exception e) %7B%0A
+//
                 
@@ -1495,32 +1495,34 @@
 ntStackTrace();%0A
+//
             %7D%0A  
@@ -1511,32 +1511,34 @@
 //            %7D%0A
+//
         %7D%0A    %7D%0A
@@ -1523,32 +1523,34 @@
   %7D%0A//        %7D%0A
+//
     %7D%0A%0A    abstr

remove shutdown hook