package cn.axzo.workflow.core.engine.job.utils;

import cn.axzo.workflow.common.constant.LogFieldConstants;
import cn.azxo.framework.common.constatns.Constants;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

@Slf4j
public class AsyncJobUtils {

    private static final String WRAPPED_PREFIX = "@@wrapped@@";

    public static String getWrappedCustomValues(String originalCustomValues) {
        WrappedJobCustomValuesInfo jobLogInfo = new WrappedJobCustomValuesInfo();
        String traceId = MDC.get(LogFieldConstants.X_REQUEST_ID);
        String cxtLogId = MDC.get(Constants.CTX_LOG_ID_MDC);
        jobLogInfo.setCtxLogId(cxtLogId);
        jobLogInfo.setXRequestId(traceId);
        jobLogInfo.setCustomValues(originalCustomValues);
        String jsonStr = JSONUtil.toJsonStr(jobLogInfo);
        return WRAPPED_PREFIX + jsonStr;
    }

    public static boolean isWrappedCustomValues(String customValues) {
        return customValues != null && !customValues.trim().isEmpty() && customValues.startsWith(WRAPPED_PREFIX);
    }

    public static WrappedJobCustomValuesInfo convert2WrappedCustomValuesInfo(String wrappedCustomValues) {
        WrappedJobCustomValuesInfo bean = null;
        if (isWrappedCustomValues(wrappedCustomValues)) {
            try {
                String str = StringUtils.substring(wrappedCustomValues, WRAPPED_PREFIX.length());
                bean = JSONUtil.toBean(str, WrappedJobCustomValuesInfo.class);
            } catch (Exception e) {
                log.warn(e.getMessage(), e);
            }
        }
        return bean;
    }

    @Data
    public static final class WrappedJobCustomValuesInfo {
        private String xRequestId;
        private String ctxLogId;
        private String customValues;
    }
}
