'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.update = updateData;
const search = __importStar(require("./search.js"));
const globalSchema = __importStar(require("../utility/globalSchema.js"));
const harper_logger_ts_1 = __importDefault(require("../utility/logging/harper_logger.js"));
const write = __importStar(require("./insert.js"));
const clone_1 = __importDefault(require("clone"));
const alasql = __importStar(require("alasql"));
const alasqlFunctionImporter_ts_1 = __importDefault(require("../sqlTranslator/alasqlFunctionImporter.js"));
const util = __importStar(require("util"));
const pGetTableSchema = util.promisify(globalSchema.getTableSchema);
const pSearch = util.promisify(search.search);
const terms = __importStar(require("../utility/hdbTerms.js"));
const hdbUtils = __importStar(require("../utility/common_utils.js"));
//here we call to define and import custom functions to alasql
(0, alasqlFunctionImporter_ts_1.default)(alasql);
const SQL_UPDATE_ERROR_MSG = 'There was a problem performing this update. Please check the logs and try again.';
/**
 * This method is used specifically for SQL UPDATE statements.
 * @method update
 * @param statement
 * @param hdb_user
 * @return
 */
async function updateData({ statement, hdb_user }) {
    let tableInfo = await pGetTableSchema(statement.table.databaseid, statement.table.tableid);
    let update_record = createUpdateRecord(statement.columns);
    //convert this update statement to a SQL search capable statement
    hdbUtils.backtickASTSchemaItems(statement);
    let { table: from, where } = statement;
    let tableClone = (0, clone_1.default)(from);
    let whereString = hdbUtils.isEmpty(where) ? '' : ` WHERE ${where.toString()}`;
    let selectString = `SELECT ${tableInfo.hash_attribute} FROM ${from.toString()} ${whereString}`;
    let searchStatement = alasql.parse(selectString).statements[0];
    //let result = await transaction.writeTransaction(tableInfo.schema, tableInfo.name, async () => {
    let records = await pSearch(searchStatement);
    let newRecords = buildUpdateRecords(update_record, records);
    return updateRecords(tableClone, newRecords, hdb_user);
    //});
    //await write.flush({ schema: tableInfo.schema, table: tableInfo.name });
    //return result;
}
/**
 * creates a json object based on the AST
 * @param columns
 */
function createUpdateRecord(columns) {
    try {
        let record = {};
        columns.forEach((column) => {
            if ('value' in column.expression) {
                record[column.column.columnid] = column.expression.value ?? null;
            }
            else {
                record[column.column.columnid] = alasql.compile(`SELECT ${column.expression.toString()} AS [${terms.FUNC_VAL}] FROM ?`);
            }
        });
        return record;
    }
    catch (err) {
        harper_logger_ts_1.default.error(err);
        throw new Error(SQL_UPDATE_ERROR_MSG);
    }
}
/**
 * Description
 * @method buildUpdateRecords
 * @param {{}} update_record
 * @param {[]} records
 * @return
 */
function buildUpdateRecords(update_record, records) {
    if (hdbUtils.isEmptyOrZeroLength(records)) {
        return [];
    }
    return records.map((record) => Object.assign(record, update_record));
}
/**
 * Description
 * @method updateRecords
 * @param  table
 * @param {[{}]} records
 * @param {{}} hdb_user
 * @return
 */
async function updateRecords(table, records, hdb_user) {
    let updateObject = {
        operation: 'update',
        schema: table.databaseid_orig,
        table: table.tableid_orig,
        records,
        hdb_user,
    };
    let res = await write.update(updateObject);
    try {
        // We do not want the API returning the new attributes property.
        delete res.new_attributes;
        delete res.txn_time;
    }
    catch (deleteErr) {
        harper_logger_ts_1.default.error(`Error delete new_attributes from update response: ${deleteErr}`);
    }
    return res;
}
//# sourceMappingURL=update.js.map