"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.StartAllWhatsAppsSessions = void 0;
const path_1 = __importDefault(require("path"));
const AutoRestore_1 = __importDefault(require("../../helpers/AutoRestore"));
const DeleteDirectory_1 = require("../../helpers/DeleteDirectory");
const RestoreControll_1 = require("../../helpers/RestoreControll");
// import { insertOrUpeateWhatsCache, loadWhatsappCache, searchWhatsappCache } from "../../helpers/WhatsCache";
const socket_1 = require("../../libs/socket");
const Whatsapp_1 = __importDefault(require("../../models/Whatsapp"));
const ListWhatsAppsService_1 = __importDefault(require("../WhatsappService/ListWhatsAppsService"));
const fs = require('fs');
require("../../helpers/SchedulingNotifySendMessage");
require("../../helpers/WhoIsOnlineMonitor");
const TicketCache_1 = require("../../helpers/TicketCache");
const ContactsCache_1 = require("../../helpers/ContactsCache");
const SchedulingNotifyCache_1 = require("../../helpers/SchedulingNotifyCache");
const CreateSessionDir_1 = require("../../helpers/CreateSessionDir");
let counter = 0;
const StartAllWhatsAppsSessions = () => __awaiter(void 0, void 0, void 0, function* () {
    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()
    CreateSessionDir_1.createSessionDir();
    RestoreControll_1.delRestoreControllFile();
    const whatsapps = yield ListWhatsAppsService_1.default();
    if (whatsapps.length > 0) {
        whatsapps.forEach((whatsapp) => __awaiter(void 0, void 0, void 0, function* () {
            // StartWhatsAppSession(whatsapp); 
            const sourcePath = path_1.default.join(process.cwd(), `.wwebjs_auth/`, `session-bd_${whatsapp.id}`);
            if (fs.existsSync(sourcePath)) {
                yield DeleteDirectory_1.removeDir(sourcePath);
                console.log('Directory deleted on start process: ', sourcePath);
            }
            else {
                console.log('Directory not found to delete on start process: ', sourcePath);
            }
            yield whatsapp.update({ status: "RESTORING" });
            // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
            //   status: "RESTORING",
            // })
            const io = socket_1.getIO();
            io.emit("whatsappSession", {
                action: "update",
                session: whatsapp
            });
            console.log('1 counter: ', counter);
            setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
                let whats = yield Whatsapp_1.default.findOne({ where: { id: whatsapp.id } });
                if (whats && whats.status !== 'CONNECTED') {
                    let lstRestore = RestoreControll_1.getRestoreControll();
                    console.log('---------> lstRestore: ', lstRestore);
                    if (Object.keys(lstRestore.filter((e) => +e.id == +whatsapp.id)).length) {
                        console.log(` EXECUTING RESTORING ON whatsappId: ${whatsapp.id}`);
                    }
                    else {
                        yield AutoRestore_1.default(whatsapp.id);
                    }
                }
            }), counter);
            counter += 57000;
        }));
    }
});
exports.StartAllWhatsAppsSessions = StartAllWhatsAppsSessions;
