package cd.casic.ci.process.engine.manager.impl;

import cd.casic.ci.process.engine.manager.PostHandlerManager;
import cd.casic.ci.process.engine.postHandler.ExecuteTaskPostHandler;
import cd.casic.ci.process.process.dataObject.history.PipPipelineHisInstance;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@Slf4j
public class MemoryPostHandlerManager implements PostHandlerManager {
    private final ConcurrentHashMap<String, List<ExecuteTaskPostHandler>> handlerMap = new ConcurrentHashMap<>();
    @Resource
    private ThreadPoolTaskExecutor postHandlerExecutor;
    @Override
    public void registerPostHandler(ExecuteTaskPostHandler handler) {
        if (handler==null|| StringUtils.isEmpty(handler.getPipelineId())) {
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"注册后置处理器失败");
        }
        List<ExecuteTaskPostHandler> orDefault = handlerMap.getOrDefault(handler.getPipelineId(), new CopyOnWriteArrayList<>());
        orDefault.add(handler);
        handlerMap.put(handler.getPipelineId(),orDefault);
    }

    @Override
    public void executePostHandler(PipPipelineHisInstance hisInstance) {
        String pipelineId = hisInstance.getPipelineId();
        List<ExecuteTaskPostHandler> pipExecutePostHandlers = handlerMap.get(pipelineId);
        if (CollectionUtils.isEmpty(pipExecutePostHandlers)) {
            return;
        }
        for (ExecuteTaskPostHandler postHandler : pipExecutePostHandlers) {
            postHandlerExecutor.submit(()->{
                try {
                    postHandler.executeAfterDone(hisInstance);
                } catch (Exception e) {
                    log.error("后置执行失败",e);
                }
            });
        }
    }
}
