"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const GenericTokenParser_1 = require("../../../core/parsing/GenericTokenParser");
const SqlNode_1 = require("./SqlNode");
class TextSqlNode extends SqlNode_1.SqlNode {
    constructor(text) {
        super();
        this.text = text;
    }
    async getSql(paramMap, parameters = []) {
        this.parameters = parameters;
        return ((await TextSqlNode.parseSql(this.text, paramMap, parameters)) +
            (await this.executeChildren(paramMap, parameters)).trim());
    }
    static async parseSql(sql, varMap, parameters) {
        // 处理?{}参数
        sql = await TextSqlNode.IF_TOKEN_PARSER.parse(sql.trim(), async (text) => {
            let ifTrue = false;
            const val = await TextSqlNode.IF_PARAM_TOKEN_PARSER.parse('?{' + text, param => {
                ifTrue = new Function(...Object.keys(varMap), `return ${param}`)(...Object.values(varMap));
                return null;
            });
            return ifTrue ? val : '';
        });
        // 处理${}参数
        sql = await TextSqlNode.CONCAT_TOKEN_PARSER.parse(sql, async (text) => typeof varMap[text] === 'string'
            ? `'${varMap[text]}'`
            : (varMap[text] || '').toString());
        // 处理#{}参数
        sql = await TextSqlNode.REPLACE_TOKEN_PARSER.parse(sql, async (text) => {
            const value = varMap[text];
            if (value == null) {
                parameters.push(null);
                return '?';
            }
            try {
                //对数组自动展开
                if (value instanceof Array) {
                    parameters.push(...value);
                    return Array.from({ length: value.length })
                        .map(() => '?')
                        .join(',');
                }
                else {
                    parameters.push(value);
                    return '?';
                }
            }
            catch (e) {
                parameters.push(value);
                return '?';
            }
        });
        return sql;
    }
}
exports.default = TextSqlNode;
TextSqlNode.CONCAT_TOKEN_PARSER = new GenericTokenParser_1.default('${', '}', false);
TextSqlNode.REPLACE_TOKEN_PARSER = new GenericTokenParser_1.default('#{', '}', true);
TextSqlNode.IF_TOKEN_PARSER = new GenericTokenParser_1.default('?{', '}', true);
TextSqlNode.IF_PARAM_TOKEN_PARSER = new GenericTokenParser_1.default('?{', ',', true);
//# sourceMappingURL=TextSqlNode.js.map