"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.removeWbot = exports.getWbot = exports.initWbot = void 0;
const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
const whatsapp_web_js_1 = require("whatsapp-web.js");
const socket_1 = require("./socket");
const Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const logger_1 = require("../utils/logger");
const wbotMessageListener_1 = require("../services/WbotServices/wbotMessageListener");
const fs = require('fs');
const CopyFolder_1 = require("../helpers/CopyFolder");
const path_1 = __importDefault(require("path"));
const DeleteDirectory_1 = require("../helpers/DeleteDirectory");
const sessions = [];
let backupSession = [];
const ListWhatsAppsNumber_1 = __importDefault(require("../services/WhatsappService/ListWhatsAppsNumber"));
let miliseconds = [1000, 2000, 3000];
const syncUnreadMessages = (wbot) => __awaiter(void 0, void 0, void 0, function* () {
    const chats = yield wbot.getChats();
    /* eslint-disable no-restricted-syntax */
    /* eslint-disable no-await-in-loop */
    for (const chat of chats) {
        if (chat.unreadCount > 0) {
            const unreadMessages = yield chat.fetchMessages({
                limit: chat.unreadCount
            });
            for (const msg of unreadMessages) {
                // console.log('--BACKEND MSG: ', msg)
                yield wbotMessageListener_1.handleMessage(msg, wbot);
            }
            yield chat.sendSeen();
        }
    }
});
const initWbot = (whatsapp, backupSessionRestore = false) => __awaiter(void 0, void 0, void 0, function* () {
    return new Promise((resolve, reject) => {
        try {
            const io = socket_1.getIO();
            const sessionName = whatsapp.name;
            let sessionCfg;
            if (whatsapp && whatsapp.session) {
                sessionCfg = JSON.parse(whatsapp.session);
            }
            //NOVA OPÇÃO MD
            // const wbot: Session = new Client({
            //   session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }),
            //   puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
            // });
            // usando instancia do chrome
            // const wbot: Session = new Client({
            //   session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }),
            //   // puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
            //   puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN ||  '/usr/bin/google-chrome-stable'  },
            // });
            const args = process.env.CHROME_ARGS || "";
            const wbot = new whatsapp_web_js_1.Client({
                session: sessionCfg,
                authStrategy: new whatsapp_web_js_1.LocalAuth({ clientId: 'bd_' + whatsapp.id }),
                puppeteer: {
                    executablePath: process.env.CHROME_BIN || undefined,
                    // @ts-ignore
                    browserWSEndpoint: process.env.CHROME_WS || undefined,
                    args: args.split(' ')
                }
            });
            wbot.initialize();
            wbot.on("qr", (qr) => __awaiter(void 0, void 0, void 0, function* () {
                if (!backupSession.includes(whatsapp.id)) {
                    backupSession.push(whatsapp.id);
                }
                console.log('************** QRCODE whatsapp.id: ', whatsapp.id, '  | backupSession: ', backupSession);
                logger_1.logger.info("Session:", sessionName);
                qrcode_terminal_1.default.generate(qr, { small: true });
                yield whatsapp.update({ qrcode: qr, status: "qrcode", retries: 0 });
                // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { qrcode: qr, status: "qrcode", retries: 0 })
                const sessionIndex = sessions.findIndex(s => s.id === whatsapp.id);
                if (sessionIndex === -1) {
                    wbot.id = whatsapp.id;
                    sessions.push(wbot);
                }
                io.emit("whatsappSession", {
                    action: "update",
                    session: whatsapp
                });
            }));
            wbot.on("authenticated", (session) => __awaiter(void 0, void 0, void 0, function* () {
                logger_1.logger.info(`Session: ${sessionName} AUTHENTICATED`);
            }));
            wbot.on("auth_failure", (msg) => __awaiter(void 0, void 0, void 0, function* () {
                console.error(`Session: ${sessionName} AUTHENTICATION FAILURE! Reason: ${msg}`);
                if (whatsapp.retries > 1) {
                    yield whatsapp.update({ session: "", retries: 0 });
                    // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { session: "", retries: 0 })
                }
                const retry = whatsapp.retries;
                yield whatsapp.update({
                    status: "DISCONNECTED",
                    retries: retry + 1
                });
                // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
                //   status: "DISCONNECTED",
                //   retries: retry + 1
                // })
                io.emit("whatsappSession", {
                    action: "update",
                    session: whatsapp
                });
                reject(new Error("Error starting whatsapp session."));
            }));
            wbot.on("ready", () => __awaiter(void 0, void 0, void 0, function* () {
                logger_1.logger.info(`Session: ${sessionName} READY`);
                if (whatsapp.name.includes(wbot.info["wid"]["user"])) {
                    console.log('-----------------> THIS IS THE RIGHT NUMBER');
                }
                else {
                    console.log('-----------------> THIS IS THE WRONG NUMBER');
                    let read_number = wbot.info["wid"]["user"];
                    yield wbot.logout();
                    io.emit("whatsappSession", {
                        action: "error",
                        msg: `Numero lido: ${read_number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`
                    });
                    return;
                }
                yield whatsapp.update({
                    status: "CONNECTED",
                    qrcode: "",
                    retries: 0,
                    number: wbot.info["wid"]["user"]
                });
                // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, whatsapp)
                io.emit("whatsappSession", {
                    action: "update",
                    session: whatsapp
                });
                const sessionIndex = sessions.findIndex(s => s.id === whatsapp.id);
                if (sessionIndex === -1) {
                    console.log('WBOT ADD ID: ', whatsapp.id);
                    wbot.id = whatsapp.id;
                    sessions.push(wbot);
                }
                wbot.sendPresenceAvailable();
                yield syncUnreadMessages(wbot);
                resolve(wbot);
                console.log(`>>>>>>>>>>>>>>>>>>>>>>>>> BACKUP SESSION whatsapp.id ${whatsapp.id} | backupSession: ${backupSession}`);
                const whatsIndex = backupSession.findIndex((id) => id === +whatsapp.id);
                console.log('               whatsIndex: ', whatsIndex);
                if (whatsIndex !== -1 || backupSessionRestore) {
                    if (whatsIndex !== -1) {
                        backupSession.splice(whatsIndex, 1);
                    }
                    setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
                        const sourcePath = path_1.default.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whatsapp.id}`);
                        const destPath = path_1.default.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`);
                        if (fs.existsSync(path_1.default.join(__dirname, `../../.wwebjs_auth/sessions`))) {
                            yield DeleteDirectory_1.removeDir(destPath);
                            // copy the good session for backup dir
                            CopyFolder_1.copyFolder(sourcePath, destPath);
                        }
                        else {
                            console.log('Directory not found to copy: ', destPath);
                        }
                        console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`);
                    }), 90000);
                    console.log('                                PASSOU NO TIMEOUT whatsapp.id: ', whatsapp.id);
                }
            }));
        }
        catch (err) {
            logger_1.logger.error(`${err}`);
        }
    });
});
exports.initWbot = initWbot;
const getWbot = (whatsappId) => __awaiter(void 0, void 0, void 0, function* () {
    console.log('getWbot whatsappId: ', whatsappId);
    let whatsapp = yield Whatsapp_1.default.findByPk(whatsappId, {
        attributes: ["url"]
    });
    if (whatsapp && whatsapp.status != 'CONNECTED') {
        let listWhatsapp = null;
        // listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
        if (!listWhatsapp) {
            listWhatsapp = yield ListWhatsAppsNumber_1.default(whatsappId, 'CONNECTED');
        }
        if (listWhatsapp.whatsapps && listWhatsapp.whatsapps.length > 0) {
            console.log('----------> getWbot has changed the whatsappId: ', listWhatsapp.whatsapps[0].id);
            whatsapp = yield Whatsapp_1.default.findByPk(listWhatsapp.whatsapps[0].id, {
                attributes: ["url"]
            });
        }
    }
    if (whatsapp && (whatsapp.url && whatsapp.url.length > 0)) {
        return whatsapp.url;
    }
    return null;
    // const sessionIndex = sessions.findIndex(s => s.id === whatsappId);
    // if (sessionIndex === -1) {
    //   throw new AppError("ERR_WAPP_NOT_INITIALIZED");
    // }
    // return sessions[sessionIndex];
});
exports.getWbot = getWbot;
const removeWbot = (whatsappId) => {
    try {
        const sessionIndex = sessions.findIndex(s => s.id === whatsappId);
        if (sessionIndex !== -1) {
            console.log('WBOT REMOVED ID: ', whatsappId);
            sessions[sessionIndex].destroy();
            sessions.splice(sessionIndex, 1);
        }
    }
    catch (err) {
        logger_1.logger.error(`${err}`);
    }
};
exports.removeWbot = removeWbot;
