package com.fireflysource.common.lifecycle;

import com.fireflysource.common.func.Callback;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;

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

public abstract class AbstractLifeCycle implements LifeCycle {

    private static final List<Callback> stopActions = new CopyOnWriteArrayList<>();

    static {
        try {
            Runtime.getRuntime().addShutdownHook(new Thread(AbstractLifeCycle::stopAll, "the firefly shutdown thread"));
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    protected AtomicBoolean start = new AtomicBoolean(false);

    public AbstractLifeCycle() {
        stopActions.add(this::stop);
    }

    @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)) {
            destroy();
        }
    }

    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();
            }
        }
    }

}

@@ -491,34 +491,16 @@
 tatic %7B%0A
-        try %7B%0A    
         
@@ -612,98 +612,8 @@
 ));%0A
-        %7D catch (Exception e) %7B%0A            System.err.println(e.getMessage());%0A        %7D%0A
     
@@ -676,16 +676,66 @@
 (false);
+%0A    protected Callback stopCallback = this::stop;
 %0A%0A    pu
@@ -785,26 +785,28 @@
 ons.add(
-this::stop
+stopCallback
 );%0A    %7D
@@ -1203,24 +1203,70 @@
  destroy();%0A
+            stopActions.remove(stopCallback);%0A
         %7D%0A  

remove stop hook.