package org.zstack.core;

import org.zstack.header.exception.CloudRuntimeException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by xing5 on 2016/6/23.
 */
public class MessageCommandRecorder {
    private static Class starter;

    private static List<Class> followers = new ArrayList<>();

    public static void start(Class s) {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        if (starter != null) {
            throw new RuntimeException(String.format("already a starter[%s] here", starter));
        }

        starter = s;
    }

    public static void record(String c) {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        try {
            followers.add(Class.forName(c));
        } catch (ClassNotFoundException e) {
            throw new CloudRuntimeException(e);
        }
    }

    public static void record(Class c) {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        followers.add(c);
    }

    public static List<Class> end() {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return null;
        }

        List<Class> ret = followers.stream().collect(Collectors.toList());
        reset();
        return ret;
    }

    public static void reset() {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        starter = null;
        followers = new ArrayList<>();
    }

    public static String endAndToString() {
        if (!CoreGlobalProperty.UNIT_TEST_ON) {
            return null;
        }

        StringBuilder sb = new StringBuilder(String.format("\n\nCALLING CHAIN FOR: %s", starter));
        for (Class c : followers) {
            sb.append(String.format("\n ---> %s", c));
        }

        reset();
        return sb.toString();
    }
}

@@ -292,16 +292,53 @@
 tarter;%0D
+%0A    private static boolean enabled;%0D
 %0A%0D%0A    p
@@ -405,40 +405,31 @@
     
-public static void start(Class s
+static boolean needRun(
 ) %7B%0D
@@ -429,37 +429,39 @@
 un() %7B%0D%0A        
-if (!
+return 
 CoreGlobalProper
@@ -467,32 +467,118 @@
 rty.UNIT_TEST_ON
+ && enabled;%0D%0A    %7D%0D%0A%0D%0A    public static void start(Class s) %7B%0D%0A        if (!needRun()
 ) %7B%0D%0A           
@@ -592,32 +592,59 @@
 ;%0D%0A        %7D%0D%0A%0D%0A
+        enabled = true;%0D%0A%0D%0A
         if (star
@@ -858,39 +858,17 @@
 f (!
-CoreGlobalProperty.UNIT_TEST_ON
+needRun()
 ) %7B%0D
@@ -1137,39 +1137,17 @@
 f (!
-CoreGlobalProperty.UNIT_TEST_ON
+needRun()
 ) %7B%0D
@@ -1273,39 +1273,17 @@
 f (!
-CoreGlobalProperty.UNIT_TEST_ON
+needRun()
 ) %7B%0D
@@ -1497,39 +1497,17 @@
 f (!
-CoreGlobalProperty.UNIT_TEST_ON
+needRun()
 ) %7B%0D
@@ -1533,32 +1533,58 @@
 ;%0D%0A        %7D%0D%0A%0D%0A
+        enabled = false;%0D%0A
         starter 
@@ -1703,39 +1703,17 @@
 f (!
-CoreGlobalProperty.UNIT_TEST_ON
+needRun()
 ) %7B%0D

make MessageCommandRecorder safer