package net.northking.cctp.element.basic.utils;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.exception.ExecuteException;

/**
 * ContextUtil
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
@Slf4j
public class ContextUtil {

    /**
     * 设置组件输出
     */
    public static void setResult(IExecuteContext context, String key, Object value) {
        String v = value != null ? value.toString() : null;
        if (StrUtil.isNotBlank(key)) {
            try {
                if (key.contains("#{") && key.contains("}")) {
                    String keyValue = ReUtil.get("(?<=\\#\\{)(.+?)(?=\\})", key, 1);
                    // #{} 全局变量
                    context.setProjectGlobalVariable(keyValue, v);
                }
                if (key.contains("${") && key.contains("}")) {
                    String keyValue = ReUtil.get("(?<=\\$\\{)(.+?)(?=\\})", key, 1);
                    // #{} 脚本变量
                    context.setVariable(keyValue, v);
                }
            } catch (Exception e) {
                throw new ExecuteException("上下文参数设置异常", e);
            }
        }
    }

    /**
     * 执行Boolean表达式
     */
    public static boolean evalBooleanExpression(IExecuteContext context, String expression) {
        Object result = context.evalExpression(expression);
        if (result instanceof Boolean) {
            return (Boolean) result;
        }
        throw new ExecuteException("条件表达式格式语法错误：" + expression);
    }

}
