"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const unflatten = require('flat').unflatten;
var flatten = require('flat');
const TicketCache_1 = require("./TicketCache");
const Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const deleteWhatsappCache = (hash) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    const whatsapp_cache = yield redis.hgetall(hash);
    try {
        if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {
            yield redis.del(hash);
            console.log(`Whatsapp cache number ${whatsapp_cache['number']} deleted!`);
        }
        else {
            console.log('WHATSAPP CACHE NOT FOUND!');
        }
    }
    catch (error) {
        console.log(`There was an error on deleteWhatsappCache:  ${error}`);
    }
    // await redis.quit()
});
const updateWhatsappCache = (hash, json_object) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    const pipeline = redis.pipeline();
    let entries = Object.entries(json_object);
    entries.forEach((e) => {
        pipeline.hset(hash, e[0], e[1]);
    });
    yield pipeline.exec(() => { console.log("whatsapp Key/value inserted/updated"); });
    // await redis.quit()
});
const updateWhatsappCacheById = (hash, update_fields) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    const whatsapp_cache = yield redis.hgetall(hash);
    try {
        if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {
            // update_fields.escaped_name = escapeCharCache(update_fields.name)
            yield updateWhatsappCache(hash, update_fields);
            console.log(`WHATSAPP ${whatsapp_cache['number']} CACHE WAS UPDATED!`);
        }
        else {
            console.log('WHATSAPP CACHE NOT FOUND!');
        }
    }
    catch (error) {
        console.log(`There was an error on updateWhatsappCacheById:  ${error}`);
    }
    // await redis.quit()
});
// const createOrUpdateContactCache = async (hash: any, contact: any) => {
//     const redis: any = await redisConn();
//     if(!redis) return
//    //  if (redis.status !== 'connect') return
//     if (contact.name) {
//         contact.escaped_name = escapeCharCache(contact.name)
//     }
//     await redis.hmset(hash, contact);
//     redis.quit()
// }
function searchWhatsappCache(id, status) {
    return __awaiter(this, void 0, void 0, function* () {
        const redis = yield TicketCache_1.redisConn();
        if (!redis)
            return;
        //  if (redis.status !== 'connect') return null
        const number_cache = yield redis.hgetall(`whatsapp:${id}`);
        if (Object.entries(number_cache).length == 0) {
            // await redis.quit()
            return [];
        }
        // console.log('NUMBER_CACHED: ', number_cache)
        //	@x:foo @y:bar
        const response = yield redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC');
        // await redis.quit()
        if (response.length === 1) {
            return [];
        }
        const results = [];
        for (let n = 2; n < response.length; n += 2) {
            const result = {};
            const fieldNamesAndValues = response[n];
            for (let m = 0; m < fieldNamesAndValues.length; m += 2) {
                const k = fieldNamesAndValues[m];
                const v = fieldNamesAndValues[m + 1];
                result[k] = v;
            }
            results.push(result);
        }
        return results;
    });
}
const insertOrUpeateWhatsCache = (hash, whatsapp) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    if (Array.isArray(whatsapp)) {
        const pipeline = redis.pipeline();
        for (let i = 0; i < whatsapp.length; i++) {
            pipeline.hmset(hash, whatsapp[i]);
        }
        yield pipeline.exec(() => { console.log(`${whatsapp.length} WHATSAPP INSERTED IN CACHE!`); });
    }
    else {
        yield redis.hmset(hash, JSON.parse(JSON.stringify(whatsapp)));
        console.log(`WHATSAPP ID ${whatsapp.id} INSERTED OR UPADTED IN CACHE!`);
    }
    // await redis.quit()
});
const loadWhatsappCache = () => __awaiter(void 0, void 0, void 0, function* () {
    yield createWhatsappIndexCache('idx_whatsapp');
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    let whatsapps = yield Whatsapp_1.default.findAll({ raw: true });
    const pipeline = redis.pipeline();
    for (let i = 0; i < whatsapps.length; i++) {
        whatsapps[i].createdAt = new Date(whatsapps[i].createdAt).toISOString();
        whatsapps[i].updatedAt = new Date(whatsapps[i].updatedAt).toISOString();
        // whatsapps[i].escaped_name = escapeCharCache(whatsapps[i].name)
        pipeline.hmset(`whatsapp:${whatsapps[i].id}`, whatsapps[i]);
    }
    yield pipeline.exec(() => { console.log(`${whatsapps.length} WHATSAPPS INSERTED IN CACHE!`); });
    // await redis.quit()
});
const createWhatsappIndexCache = (hashIndex) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    try {
        const lst_index_redis = yield redis.call('FT._LIST');
        if (lst_index_redis.includes(hashIndex)) {
            console.log('entrou...');
            yield redis.call('FT.DROPINDEX', hashIndex);
        }
        const response = yield redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA', 'id', 'NUMERIC', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT', 'SORTABLE');
        console.log('Whatsapp index created: ', response);
    }
    catch (error) {
        console.log('There was an error on createWhatsappIndexCache: ', error);
    }
    // await redis.quit()
});
