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

import lombok.Getter;

import java.util.*;

@Getter
public enum ContextStateEnum {
    INIT(0,"初始化"),
    READY(1,"就绪"),
    RUNNING(2,"运行"),
    SUSPEND(3,"挂起"),
    STOP(-1,"停止"),
    HAPPY_ENDING(4,"执行成功"),
    BAD_ENDING(5,"执行失败"),
    SKIP_TO(6,"跳过"),
    //如果状态依然为执行失败，开始重新执行就会直接因为存在执行错误而结束，所以从错误处重新执行引入了这个新状态
    ERROR_EXECUTE_READY(7,"从错误处执行准备完毕")
    ;

    private Integer code;
    private String msg;
    private static final Map<ContextStateEnum, Set<ContextStateEnum>> TRANSITIONS = new EnumMap<>(ContextStateEnum.class);

    static {
        TRANSITIONS.put(INIT, Set.of(READY, SUSPEND, BAD_ENDING, STOP));
        TRANSITIONS.put(READY, Set.of(READY,RUNNING, SUSPEND, BAD_ENDING, STOP));
        TRANSITIONS.put(RUNNING, Set.of(RUNNING,SUSPEND, HAPPY_ENDING, BAD_ENDING, STOP,SKIP_TO));
        TRANSITIONS.put(SUSPEND, Set.of(SUSPEND,INIT, READY, BAD_ENDING, RUNNING,STOP));
        //...初始化其他状态转移关系
        TRANSITIONS.put(SKIP_TO,Set.of(HAPPY_ENDING));
        TRANSITIONS.put(BAD_ENDING,Set.of(ERROR_EXECUTE_READY));
        TRANSITIONS.put(ERROR_EXECUTE_READY,Set.of(ERROR_EXECUTE_READY,READY,RUNNING,SUSPEND,SKIP_TO,BAD_ENDING,HAPPY_ENDING));
//        TRANSITIONS.put(HAPPY_ENDING,Set.of(RUNNING));
    }

    ContextStateEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;

    }
    public static Boolean canGoto(ContextStateEnum from,ContextStateEnum to){
        try {
            if (Objects.isNull(from) || Objects.isNull(to)) {
                return false;
            }
            return TRANSITIONS.get(from).contains(to);
        } catch (Exception e){
            return false;
        }
    }
    public static ContextStateEnum getByCode(Integer code){
        for (ContextStateEnum value : values()) {
            if (value.getCode().equals(code)) {
                return value;
            }
        }
        return null;
    }
}
