package link.at17.mid.tushare.config;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.BeanCreationException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConstructionGuard {
    private static final ThreadLocal<Set<Class<?>>> constructing = ThreadLocal.withInitial(HashSet::new);

    public static boolean isConstructing(Class<?> clazz) {
        return constructing.get().contains(clazz);
    }

    public static void enter(Class<?> clazz) {
        log.debug("Enter construction for {}", clazz.toString());
        if (isConstructing(clazz)) {
            StringBuilder sb = new StringBuilder();
            sb.append("Class ")
              .append(clazz.getName())
              .append(" is being constructed but is seems like circular involving.");
            String msg = sb.toString();
            log.error(msg);
            throw new BeanCreationException(msg);
        }
        constructing.get().add(clazz);
    }

    public static void exit(Class<?> clazz) {
        constructing.get().remove(clazz);
        log.debug("Exit construction for {}", clazz.toString());
    }
}