import { ExperimentStatus } from '@/enums';
import { NodeStatus } from '@/types';
import { parseJsonText } from './index';

/**
 * 获取工作流节点
 *
 * @param node_status - 流水线workflow节点，json字符串
 * @return workflow 节点
 */
export const getWorkflowStatus = (node_status?: string | null) => {
  if (!node_status) {
    return undefined;
  }

  const nodeStatusJson = parseJsonText(node_status);
  if (!nodeStatusJson) {
    return undefined;
  }

  for (const key in nodeStatusJson) {
    if (key.startsWith('workflow')) {
      return nodeStatusJson[key];
    }
  }
  return undefined;
};

/**
 * 获取实例状态
 * 终止或者 workflowStatus 不存在时，取实例状态，否则取流水线状态
 *
 * @param instanceStatus - 实例状态
 * @param workflowStatus - 流水线workflow节点
 * @return 实例状态
 */
export const getExperimentInstanceStatus = (
  instanceStatus: ExperimentStatus,
  workflowStatus?: NodeStatus,
): ExperimentStatus => {
  return instanceStatus === ExperimentStatus.Terminated || !workflowStatus
    ? instanceStatus
    : workflowStatus?.phase;
};

/**
 * 获取实例状态
 * 终止或者 workflowStatus 不存在时，取实例状态，否则取流水线状态
 *
 * @param instanceStatus - 实例状态
 * @param workflowStatus - 流水线workflow节点
 * @return 实例状态
 */
export const getInstanceStatusInList = (
  instanceStatus: ExperimentStatus,
  node_status?: string | null,
): ExperimentStatus => {
  const workflowStatus = getWorkflowStatus(node_status);
  return getExperimentInstanceStatus(instanceStatus, workflowStatus);
};
