package cn.fateverse.query.handler.engine.impl;

import cn.fateverse.common.code.engine.JavaScriptEngine;
import cn.fateverse.common.code.model.EngineResult;
import cn.fateverse.common.core.exception.CustomException;
import cn.fateverse.query.entity.DataAdapter;
import cn.fateverse.query.enums.DataAdapterType;
import cn.fateverse.query.handler.engine.EngineExecuteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * JavaScript 代码执行器
 *
 * @author Clay
 * @date 2023-10-29  19:35
 */
@Slf4j
@Component
public class JavaScriptEngineExecuteHandler implements EngineExecuteHandler {

    @Override
    public EngineResult execute(DataAdapter dataAdapter, Object data, boolean development) {
        if (!DataAdapterType.JAVA_SCRIPT.equals(dataAdapter.getType())) {
            return null;
        }
        return JavaScriptEngine.execute(dataAdapter.getExecuteCode(), "execute" + dataAdapter.getAdapterId(), development, data);
    }

    @Override
    public Boolean preconditioning(DataAdapter dataAdapter) {
        if (!DataAdapterType.JAVA_SCRIPT.equals(dataAdapter.getType())) {
            return Boolean.FALSE;
        }
        String code = dataAdapter.getCode();
        // 正则表达式匹配类定义
        String regex = "function .*? ";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(code);
        if (matcher.find()) {
            // 执行替换操作
            String replacedCode = code.replaceFirst(regex, "function execute" + dataAdapter.getAdapterId() + "(data) ");
            dataAdapter.setExecuteCode(replacedCode);
        } else {
            throw new CustomException("请勿修改类定义");
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean remove(DataAdapter dataAdapter) {
        return Boolean.FALSE;
    }
}
