"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 path_1 = __importDefault(require("path"));
const socket_1 = require("../libs/socket");
const Message_1 = __importDefault(require("../models/Message"));
const ShowWhatsAppService_1 = __importDefault(require("../services/WhatsappService/ShowWhatsAppService"));
const logger_1 = require("../utils/logger");
const GetTicketWbot_1 = __importDefault(require("./GetTicketWbot"));
const fs_1 = __importDefault(require("fs"));
const SplitDateTime_1 = require("./SplitDateTime");
const date_fns_1 = require("date-fns");
const pt_BR_1 = __importDefault(require("date-fns/locale/pt-BR"));
const SetTicketMessagesAsRead = (ticket) => __awaiter(void 0, void 0, void 0, function* () {
    yield Message_1.default.update({ read: true }, {
        where: {
            ticketId: ticket.id,
            read: false
        }
    });
    yield ticket.update({ unreadMessages: 0 });
    try {
        const wbot = yield GetTicketWbot_1.default(ticket);
        // test del
        // throw new Error('Throw makes it go boom!')
        //
        yield wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
    }
    catch (err) {
        logger_1.logger.warn(`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`);
        //Solução para contornar erro de sessão
        if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
            const sourcePath = path_1.default.join(__dirname, `../../.wwebjs_auth/sessions/log`);
            const dateToday = SplitDateTime_1.splitDateTime(new Date(date_fns_1.format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: pt_BR_1.default })));
            const whatsapp = yield ShowWhatsAppService_1.default(ticket.whatsappId);
            if (whatsapp && whatsapp.status == 'CONNECTED') {
                let timestamp = Math.floor(Date.now() / 1000);
                fs_1.default.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error) => { });
                // await restartWhatsSession(whatsapp)
            }
        }
    }
    const io = socket_1.getIO();
    io.to(ticket.status).to("notification").emit("ticket", {
        action: "updateUnread",
        ticketId: ticket.id
    });
});
exports.default = SetTicketMessagesAsRead;
