"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 });
exports.deleteScheduleByTicketIdCache = exports.createSchedulingNotifyCache = exports.updateScheduleCacheByTicketId = exports.searchScheduleCache = exports.loadSchedulesCache = void 0;
const unflatten = require('flat').unflatten;
var flatten = require('flat');
const TicketCache_1 = require("./TicketCache");
const SchedulingNotify_1 = __importDefault(require("../models/SchedulingNotify"));
const date_fns_1 = require("date-fns");
const pt_BR_1 = __importDefault(require("date-fns/locale/pt-BR"));
const ContactsCache_1 = require("./ContactsCache");
const deleteScheduleByTicketIdCache = (ticketId) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    const schedule_cache = yield redis.hgetall(`schedule:${ticketId}`);
    try {
        if (schedule_cache && Object.keys(schedule_cache).length > 0) {
            yield redis.del(`schedule:${ticketId}`);
            console.log(`Schedule cache ticketId ${schedule_cache.ticketId} deleted!`);
        }
        else {
            console.log('SCHEDULE CACHE NOT FOUND!');
        }
    }
    catch (error) {
        console.log(`There was an error on deleteScheduleByTicketIdCache:  ${error}`);
    }
    // await redis.quit()
});
exports.deleteScheduleByTicketIdCache = deleteScheduleByTicketIdCache;
const updateScheduleCacheByTicketId = (scheduleNotify) => __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(scheduleNotify);
    entries.forEach((e) => {
        pipeline.hset(`schedule:${scheduleNotify.ticketId}`, e[0], e[1]);
    });
    yield pipeline.exec(() => { console.log("schedule Key/value inserted/updated"); });
    // await redis.quit()
});
exports.updateScheduleCacheByTicketId = updateScheduleCacheByTicketId;
const createSchedulingNotifyCache = (scheduleNotify) => __awaiter(void 0, void 0, void 0, function* () {
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return  
    let date_time = date_fns_1.format(new Date(scheduleNotify.schedulingTime), 'yyyy-MM-dd HH:mm:ss', { locale: pt_BR_1.default }).split(' ');
    delete scheduleNotify.schedulingTime;
    delete scheduleNotify.updatedAt;
    delete scheduleNotify.createdAt;
    delete scheduleNotify.schedulingDate;
    console.log('created date_time: ', date_time);
    scheduleNotify.date = date_time[0];
    scheduleNotify.date_escaped = ContactsCache_1.escapeCharCache(date_time[0]);
    scheduleNotify.hour = date_time[1].split(':')[0];
    scheduleNotify.minute = date_time[1].split(':')[1];
    yield redis.hmset(`schedule:${scheduleNotify.ticketId}`, scheduleNotify);
    console.log(`${scheduleNotify.length} SCHEDULE NOTIFY INSERTED IN CACHE!`);
    // await redis.quit()
});
exports.createSchedulingNotifyCache = createSchedulingNotifyCache;
function searchScheduleCache(date, hour, minute) {
    return __awaiter(this, void 0, void 0, function* () {
        const redis = yield TicketCache_1.redisConn();
        if (!redis)
            return;
        //  if (redis.status !== 'connect') return null
        date = ContactsCache_1.escapeCharCache(date).trim();
        const response = yield redis.call('FT.SEARCH', 'idx_schedule', `(@date_escaped:${date}) (@hour:${hour}) (@minute:${minute})`);
        // 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;
    });
}
exports.searchScheduleCache = searchScheduleCache;
const loadSchedulesCache = () => __awaiter(void 0, void 0, void 0, function* () {
    yield createScheduleIndexCache('idx_schedule');
    const redis = yield TicketCache_1.redisConn();
    if (!redis)
        return;
    //  if (redis.status !== 'connect') return
    let schedules = yield SchedulingNotify_1.default.findAll({ raw: true, attributes: ["id", "statusChatEndId", "ticketId", "schedulingTime", "message"] });
    // console.log('SCHEDULE NOTIFY CACHE2: ', schedules)
    const pipeline = redis.pipeline();
    for (let i = 0; i < schedules.length; i++) {
        let date_time = date_fns_1.format(new Date(schedules[i].schedulingTime), 'yyyy-MM-dd HH:mm:ss', { locale: pt_BR_1.default }).split(' ');
        delete schedules[i].schedulingTime;
        console.log('date_time: ', date_time);
        schedules[i].date = date_time[0];
        schedules[i].date_escaped = ContactsCache_1.escapeCharCache(date_time[0]);
        schedules[i].hour = date_time[1].split(':')[0];
        schedules[i].minute = date_time[1].split(':')[1];
        pipeline.hmset(`schedule:${schedules[i].ticketId}`, schedules[i]);
    }
    yield pipeline.exec(() => { console.log(`${schedules.length} SCHEDULES NOTIFY INSERTED IN CACHE!`); });
    // await redis.quit()
    // let test = await searchScheduleCache('2022-12-16', '18', '30')
    // console.log('--------------> TEST: ', test)
});
exports.loadSchedulesCache = loadSchedulesCache;
const createScheduleIndexCache = (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', 'schedule:', 'SCHEMA', 'id', 'TEXT', 'SORTABLE', 'date_escaped', 'TEXT', 'SORTABLE', 'hour', 'TEXT', 'SORTABLE', 'minute', 'TEXT', 'SORTABLE');
        console.log('Schedule index created: ', response);
    }
    catch (error) {
        console.log('There was an error on createScheduleIndexCache: ', error);
    }
    // await redis.quit()
});
