package com.elab.spring.componts.containers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;

import java.util.ArrayList;
import java.util.List;

/**
 * 容器刷新回调
 */
public class ContainerRefresh {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private volatile boolean isRefresh = false;
    private List<SupplierVoid> invokeMethodList = new ArrayList<>();
    private int callCount = 0;

    private static ContainerRefresh INSTACE = new ContainerRefresh();

    public static ContainerRefresh getInstance() {
        return INSTACE;
    }

    /**
     * 注册需要在容器启动完成之后回调的事件
     *
     * @param supplier
     */
    public void register(SupplierVoid supplier) {
        invokeMethodList.add(supplier);
    }

    public boolean isRefresh() {
        return isRefresh;
    }

    protected void refreshMethod(ApplicationArguments args) {

        if (isRefresh()) {
            callCount++;
            logger.warn("请注意存在重复刷新容器方法的情况！ >> " + callCount);
        }

        invokeMethodList.forEach((method) -> {
            logger.debug(">>>>>>>>>>" + method + "<<<<<<<<<<");
            method.process(args);
            logger.debug("<<<<<<<<<<" + method + ">>>>>>>>>>");
        });

        isRefresh = true;
    }

    public interface SupplierVoid {
        /**
         * Gets a result.
         *
         * @return a result
         */
        void process(ApplicationArguments args);
    }

    public static void main(String[] args) {
        ContainerRefresh.getInstance().register((arg) -> {
        });
    }
}