"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const env = require("../environment");
const db = require("../db");
const redis = require("@devlego/backend-core/redis");
const { SEPARATOR } = require("@devlego/backend-core/db");
const VARIABLE_TTL_SECONDS = 3600;
let client;
function getClient() {
    return __awaiter(this, void 0, void 0, function* () {
        if (!client) {
            client = yield new redis.Client(redis.utils.Databases.QUERY_VARS).init();
        }
        return client;
    });
}
process.on("exit", () => __awaiter(void 0, void 0, void 0, function* () {
    if (client)
        yield client.finish();
}));
exports.threadSetup = () => {
    // don't run this if not threading
    if (env.isTest() || env.DISABLE_THREADING) {
        return;
    }
    // when thread starts, make sure it is recorded
    env.setInThread();
    db.init();
};
function makeVariableKey(queryId, variable) {
    return `${queryId}${SEPARATOR}${variable}`;
}
exports.checkCacheForDynamicVariable = (queryId, variable) => __awaiter(void 0, void 0, void 0, function* () {
    const cache = yield getClient();
    return cache.get(makeVariableKey(queryId, variable));
});
exports.invalidateDynamicVariables = (cachedVars) => __awaiter(void 0, void 0, void 0, function* () {
    const cache = yield getClient();
    let promises = [];
    for (let variable of cachedVars) {
        promises.push(cache.delete(makeVariableKey(variable.queryId, variable.name)));
    }
    yield Promise.all(promises);
});
exports.storeDynamicVariable = (queryId, variable, value) => __awaiter(void 0, void 0, void 0, function* () {
    const cache = yield getClient();
    yield cache.store(makeVariableKey(queryId, variable), value, VARIABLE_TTL_SECONDS);
});
exports.formatResponse = resp => {
    if (typeof resp === "string") {
        try {
            resp = JSON.parse(resp);
        }
        catch (err) {
            resp = { response: resp };
        }
    }
    return resp;
};
exports.hasExtraData = response => {
    return (typeof response === "object" &&
        !Array.isArray(response) &&
        response &&
        response.data != null &&
        response.info != null);
};
