"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 ShowTicketService_1 = __importDefault(require("../services/TicketServices/ShowTicketService"));
const SendWhatsAppMessage_1 = __importDefault(require("../services/WbotServices/SendWhatsAppMessage"));
const ListSchedulingNotifyService_1 = __importDefault(require("../services/SchedulingNotifyServices/ListSchedulingNotifyService"));
const DeleteSchedulingNotifyService_1 = __importDefault(require("../services/SchedulingNotifyServices/DeleteSchedulingNotifyService"));
const SchedulingNotifyCache_1 = require("./SchedulingNotifyCache");
const Ticket_1 = __importDefault(require("../models/Ticket"));
const User_1 = __importDefault(require("../models/User"));
const sequelize_1 = require("sequelize");
const OmnhitDashboardSession_1 = __importDefault(require("./OmnhitDashboardSession"));
const fastFolderSize = require("fast-folder-size");
const { promisify } = require("util");
const fs = require("fs");
const { exec } = require("child_process");
let _fifo;
let scheduler_monitor;
let timeInterval = 5;
const monitor = () => __awaiter(void 0, void 0, void 0, function* () {
    let date = new Date();
    let day = date.getDate().toString().padStart(2, "0");
    let month = (date.getMonth() + 1).toString().padStart(2, "0");
    let year = date.getFullYear();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let fullDate = `${year}-${month}-${day}`;
    let dateParm = `${fullDate} ${hour.toString().padStart(2, "0")}:${minute
        .toString()
        .padStart(2, "0")}:00`;
    //console.log(dateParm);
    try {
        const { schedulingNotifies, count, hasMore } = yield ListSchedulingNotifyService_1.default({
            searchParam: dateParm,
            pageNumber: "1"
        });
        if (schedulingNotifies && schedulingNotifies.length > 0) {
            for (let i = 0; i < schedulingNotifies.length; i++) {
                const ticket = yield ShowTicketService_1.default(+schedulingNotifies[i].ticketId);
                let _ticket = yield Ticket_1.default.findOne({
                    where: {
                        contactId: ticket.contactId,
                        status: { [sequelize_1.Op.in]: ["open", "pending"] }
                    }
                });
                yield SchedulingNotifyCache_1.deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId);
                yield DeleteSchedulingNotifyService_1.default(schedulingNotifies[i].id);
                if (_ticket)
                    continue;
                if (ticket.dataValues.status == "closed") {
                    yield ticket.update({ status: "open" });
                }
                const userId = ticket.getDataValue("userId");
                let userN = "";
                if (userId) {
                    const useer = yield User_1.default.findByPk(userId);
                    if (useer) {
                        const userName = useer.getDataValue("name");
                        userN = `*${userName}:* \n`;
                    }
                }
                yield new Promise(f => setTimeout(f, 3000));
                yield SendWhatsAppMessage_1.default({
                    body: userN + schedulingNotifies[i].message,
                    ticket
                });
            }
        }
        exec("df -h /", (error, stdout, stderr) => {
            if (error) {
                console.log(`exec error: ${error.message}`);
                return;
            }
            if (stderr) {
                console.log(`exec stderr: ${stderr}`);
                return;
            }
            stdout = stdout.split(/\r?\n/);
            stdout = stdout[1].trim().split(/\s+/);
            // DISK SPACE MONITORING
            // const io = getIO();
            // io.emit("diskSpaceMonit", {
            //   action: "update",
            //   diskSpace: {
            //     size: stdout[1],
            //     used: stdout[2],
            //     available: stdout[3],
            //     use: stdout[4]
            //   }
            // });
            let data = {};
            data.diskSpace = {
                DB: process.env.DB_NAME,
                size: stdout[1],
                used: stdout[2],
                available: stdout[3],
                use: stdout[4]
            };
            data.action = "update";
            OmnhitDashboardSession_1.default(data);
        });
    }
    catch (error) {
        console.log(">>> SchedulingNotifiySendMessage.ts error: ", error);
    }
});
const SchedulingNotifySendMessage = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        clearInterval(_fifo);
        yield monitor();
    }
    catch (error) {
        console.log("error on SchedulingNotifySendMessage: ", error);
    }
    finally {
        _fifo = setInterval(SchedulingNotifySendMessage, 5000);
    }
});
_fifo = setInterval(SchedulingNotifySendMessage, 5000);
module.exports = SchedulingNotifySendMessage;
