"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 http_graceful_shutdown_1 = __importDefault(require("http-graceful-shutdown"));
const app_1 = __importDefault(require("./app"));
const socket_1 = require("./libs/socket");
const logger_1 = require("./utils/logger");
const User_1 = __importDefault(require("./models/User"));
const Whatsapp_1 = __importDefault(require("./models/Whatsapp"));
const TicketCache_1 = require("./helpers/TicketCache");
require("./helpers/CloseBotTickets");
const ContactsCache_1 = require("./helpers/ContactsCache");
const SchedulingNotifyCache_1 = require("./helpers/SchedulingNotifyCache");
const RestoreControll_1 = require("./helpers/RestoreControll");
require("./helpers/AutoCloseTickets");
require("./helpers/AutoRemoteTickets");
require("./helpers/SchedulingNotifySendMessage");
const axios_1 = __importDefault(require("axios"));
const os_1 = __importDefault(require("os"));
const LoadSettings_1 = __importDefault(require("./helpers/LoadSettings"));
const RedisClient_1 = require("./helpers/RedisClient");
const ShowUserService_1 = __importDefault(require("./services/UserServices/ShowUserService"));
const SetBotInfo_1 = require("./helpers/SetBotInfo");
const Queue_1 = __importDefault(require("./models/Queue"));
const StatusChatEnd_1 = __importDefault(require("./models/StatusChatEnd"));
const server = app_1.default.listen(process.env.PORT, () => {
    logger_1.logger.info(`Server started on port: ${process.env.PORT}`);
});
// if (global.gc) {
//   console.log(">> Starting Garbage Collector...");
//   global.gc();
// } else {
//   console.warn('No GC hook! Start your program as `node --expose-gc file.js`.');
// }
socket_1.initIO(server);
// StartAllWhatsAppsSessions();
http_graceful_shutdown_1.default(server);
(() => __awaiter(void 0, void 0, void 0, function* () {
    console.log("os.tmpdir(): ", os_1.default.tmpdir());
    yield RedisClient_1.clearAllKeys("user:*", "whatsapp:*", "queue:*", "statusChatEnd:*");
    // let messages: any = await Message.findAll({
    //   attributes: ["id", "ticketId", "body"]
    // });
    // for (const message of messages) {
    //   const { id, body, ticketId } = message;
    //   await set(`message:ticketId:${ticketId}:id:${id}`, body);
    // }
    const statusChatEnds = yield StatusChatEnd_1.default.findAll();
    for (const statusChatEnd of statusChatEnds) {
        const { id, name, farewellMessage } = statusChatEnd;
        yield RedisClient_1.set(`statusChatEnd:${id}`, { id, name, farewellMessage });
    }
    const users = yield User_1.default.findAll();
    for (const user of users) {
        const { id, name } = user;
        if (name == "botqueue") {
            const userService = yield ShowUserService_1.default(id);
            yield SetBotInfo_1.setBotInfo(userService);
        }
        yield RedisClient_1.set(`user:${id}`, { id, name });
    }
    const queues = yield Queue_1.default.findAll();
    for (const queue of queues) {
        const { id, greetingMessage, name, farewellMessage } = queue;
        yield RedisClient_1.set(`queue:${id}`, { id, name, greetingMessage, farewellMessage });
    }
    LoadSettings_1.default();
    let whatsapps = yield Whatsapp_1.default.findAll({
        attributes: ["id", "url", "phoneNumberId", "number", "greetingMessage"]
    });
    if (whatsapps && whatsapps.length > 0) {
        for (let i = 0; i < whatsapps.length; i++) {
            try {
                const { phoneNumberId, id, greetingMessage } = whatsapps[i];
                // if (phoneNumberId) {
                //   await set(
                //     `whatsapp:${whatsapps[i].dataValues.id}`,
                //     JSON.stringify({
                //       number: whatsapps[i].dataValues.number,
                //       id,
                //       greetingMessage,
                //       phoneNumberId
                //     })
                //   );
                // }
                yield RedisClient_1.set(`whatsapp:${whatsapps[i].dataValues.id}`, JSON.stringify({
                    number: whatsapps[i].dataValues.number,
                    id,
                    greetingMessage,
                    phoneNumberId
                }));
                if (phoneNumberId) {
                    continue;
                }
                console.log(`API URL: ${whatsapps[i].dataValues.url}/api/connection/status`);
                const response = yield axios_1.default.get(`${whatsapps[i].dataValues.url}/api/connection/status`, {});
                console.log(`-------> Response: ${response.data.data}`);
                if (!response) {
                    throw new Error("Response null");
                }
                if (response.data.data && response.data.data == "CONNECTED") {
                    yield whatsapps[i].update({ status: "CONNECTED" });
                }
            }
            catch (error) {
                yield whatsapps[i].update({ status: "OPENING" });
                console.log(`There was an error on try acess the api sessions ${whatsapps[i].dataValues.url}`);
            }
            yield new Promise(f => setTimeout(f, 100));
        }
    }
    if (process.env.CACHE) {
        const cacheLength = yield TicketCache_1.cacheSize();
        console.log("cacheSize: ", cacheLength);
        if (cacheLength == 0) {
            console.log("Loading from cache...");
            yield TicketCache_1.flushCache();
            yield ContactsCache_1.loadContactsCache();
            yield TicketCache_1.loadTicketsCache();
        }
        yield SchedulingNotifyCache_1.loadSchedulesCache();
        // await loadWhatsappCache()
    }
    RestoreControll_1.delRestoreControllFile();
}))();
setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
    const io = socket_1.getIO();
    console.log("Triggered socket!");
    let users = yield User_1.default.findAll({ raw: true, attributes: ["id"] });
    if (users && users.length > 0) {
        for (let i = 0; i < users.length; i++) {
            io.emit("reload_page", {
                action: "update",
                userId: users[i].id
            });
            console.log("USER ID: ", users[i].id);
            yield new Promise(f => setTimeout(f, 100));
        }
    }
}), 5000);
