package net.northking.cctp.element.mobile.ios.utils;

import cn.hutool.core.util.ReUtil;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.exception.ExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class CommonUtils {

    private static Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    public static void handleSufExecuteWait(Float sufExecuteWait) {
        if (sufExecuteWait > 0) {
            Float waitTime = sufExecuteWait * 1000;
            try {
                Thread.sleep(waitTime.longValue());
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    public static void handlePreExecuteWait(Float preExecuteWait) {
        if (preExecuteWait > 0) {
            Float waitTime = preExecuteWait * 1000;
            try {
                Thread.sleep(waitTime.longValue());
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    public static void setParamValue(IExecuteContext context, String variable, String value) {
        try {
            if (variable.contains("#{") && variable.contains("}")) {
                String keyValue = ReUtil.get("(?<=\\#\\{)(.+?)(?=\\})", variable, 1);
                // #{} 全局变量
                context.setProjectGlobalVariable(keyValue, value);
            }
            if (variable.contains("${") && variable.contains("}")) {
                String keyValue = ReUtil.get("(?<=\\$\\{)(.+?)(?=\\})", variable, 1);
                // #{} 全局变量
                context.setVariable(keyValue, value);
            }
        } catch (Exception e) {
            throw new ExecuteException(String.format("参数【%s】设置异常！！", variable));
        }
    }

    public static String handleVariable(IExecuteContext context, String text) {
        if (StringUtils.hasText(text) && (RegexUtils.containScriptVar(text) || RegexUtils.containGlobalVar(text))) {  //脚本变量
            String value = context.getVariable(text);
            logger.debug("传入text:{},使用变量：{}去拿结果，拿到的结果：{}", text, text, value);
            if (null == value) {
                throw new ExecuteException(String.format("变量【%s】不存在！", value));
            }
            return value;
        }
        return text;
    }
}
