package cd.casic.ci.process.engine.runContext;

import cd.casic.ci.process.process.dataObject.base.PipBaseElement;
import cd.casic.ci.process.process.dataObject.stage.PipStage;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.util.collection.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SecondStageRunContext extends BaseRunContext{
    public SecondStageRunContext(PipStage contextDef,Integer childCount, PipelineRunContext parentContext, Map<String, Object> localVariables) {
        super(contextDef,childCount, parentContext, LocalDateTime.now(), parentContext.getResourceId(), parentContext.getTargetVersionId(), parentContext.getTargetType(), parentContext.getGlobalVariables(), localVariables, new ConcurrentHashMap<>());
    }

    @Override
    public BaseRunContext getRunContext(String id) {
        if (this.getContextDef().getId().equals(id)) {
            return this;
        }
        Map<String, BaseRunContext> childContext = getChildContext();
        for (Map.Entry<String, BaseRunContext> entry : childContext.entrySet()) {
            BaseRunContext childRunContext = entry.getValue().getRunContext(id);
            if (childRunContext!=null) {
                return childRunContext;
            }
        }
        return null;
    }

    @Override
    public void putChildRunContext(String key, BaseRunContext context) {
        Map<String, BaseRunContext> childContext = getChildContext();
        if (context instanceof TaskRunContext) {
            childContext.put(key,context);
        } else {
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"不支持类型");
        }
    }
}
