package com.muyu.data.core;

import com.muyu.data.basics.EventStrategyHandler;
import com.muyu.data.basics.EventStrategyRouter;
import com.muyu.data.constant.EventConditions;
import com.muyu.data.constant.EventEnum;
import com.muyu.data.core.event.FenceStrategy;
import com.muyu.data.domain.Information;

import lombok.extern.log4j.Log4j2;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 存储事件节点（路由转发）
 * @Author WangXin
 * @Data 2024/10/5
 * @Version 1.0.0
 */
@Log4j2
public class IotdbStrategy
        extends EventStrategyRouter<Information, Information>
        implements EventStrategyHandler<Information, Information> {

    private static ConcurrentHashMap<EventEnum,EventStrategyRouter<Information,Information>> map = new ConcurrentHashMap<>();

    private static ExecutorService executor = Executors.newFixedThreadPool(3);
    @Override
    public Information apply(Information param) {
        return applyStrategy(param);
    }

    @Override
    protected StrategyMapper<Information, Information> registerStrategy() {
        return param -> {
            initExecuteStrategy(param);
            if (isEventMapSize()){
                log.info("[没有事件执行]");
            }else {
                for (EventEnum eventEnum : map.keySet()) {
                    executor.submit(() -> {
                        log.info("开始执行 [{}] ",eventEnum.getEventName());
                        return map.get(eventEnum);
                    });
                }
            }
            return new EndStrategy();
        };
    }

    /**
     * 初始化事件map
     * @param param 入参
     */
    private static void initExecuteStrategy(Information param){
        if (EventConditions.FENCE_STRATEGY.isExecute(param)){
            map.put(EventEnum.FENCE_EVENT,new FenceStrategy());
        }
        if (EventConditions.FAULT_STRATEGY.isExecute(param)){
            map.put(EventEnum.FAULT_EVENT,new FenceStrategy());
        }
        if (EventConditions.WARN_STRATEGY.isExecute(param)){
            map.put(EventEnum.WARN_EVENT,new FenceStrategy());
        }
    }

    /**
     * 判断事件map长度
     * @return
     */
    private static boolean isEventMapSize(){
        return map.size() > 0;
    }
}
