"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 date_fns_1 = require("date-fns");
const RedisClient_1 = require("./RedisClient");
const socket_1 = require("../libs/socket");
const controllByNumber_1 = __importDefault(require("./controllByNumber"));
const UpdateTicketService_1 = __importDefault(require("../services/TicketServices/UpdateTicketService"));
let timer;
const AutoRemoteTickets = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        let obj = yield controllByNumber_1.default();
        if (!(obj === null || obj === void 0 ? void 0 : obj.tickets))
            return;
        // console.log("remote tickets: ", obj?.tickets);
        for (const ticket of obj.tickets) {
            if (!ticket.includes("open") || ticket.includes("messageDateTime"))
                continue;
            const regex = /"updatedAt":"([^"]+)"/;
            let match = ticket.match(regex);
            const updatedAt = match ? match[1] : null;
            console.log("updatedAt: ", updatedAt);
            let timeDiff = date_fns_1.intervalToDuration({
                start: new Date(updatedAt),
                end: new Date()
            });
            console.log("----------> idle time timeDiff: ", timeDiff);
            if (timeDiff.minutes > 2) {
                match = ticket.match(/"id":(\d+)/);
                let ticketId = match ? match[1] : null;
                console.log("ticketId: ", ticketId);
                ticketId = JSON.parse(ticketId);
                let ticketRemote = yield RedisClient_1.get({
                    key: `remote:ticketId:${ticketId}`
                });
                if (ticketRemote) {
                    ticketRemote = JSON.parse(ticketRemote);
                    ticketRemote = Object.assign(Object.assign({}, ticketRemote), { status: "pending" });
                    RedisClient_1.set(`remote:ticketId:${ticketId}`, JSON.stringify(ticketRemote));
                    yield UpdateTicketService_1.default({
                        ticketData: {
                            status: "pending",
                            userId: null
                        },
                        ticketId
                    });
                    const io = socket_1.getIO();
                    io.emit("remoteTickesControllIdleOpen", {
                        action: "update",
                        ticketId
                    });
                }
            }
        }
        for (const ticket of obj.tickets) {
            if (!ticket.includes("messageDateTime"))
                continue;
            let match = ticket.match(/"messageDateTime":("[^"]*")/);
            let messageDateTime = match ? match[1] : null;
            console.log("messageDateTime: ", messageDateTime);
            match = ticket.match(/"whatsappId":(\d+)/);
            let whatsappId = match ? match[1] : null;
            console.log("whatsappId: ", whatsappId);
            const whatsapp = yield RedisClient_1.get({
                key: `whatsapp:${whatsappId}`
            });
            match = whatsapp.match(/"number":"(\d+)"/);
            let number = match ? match[1] : null;
            console.log("number: ", number);
            match = ticket.match(/"id":(\d+)/);
            let ticketId = match ? match[1] : null;
            console.log("ticketId: ", ticketId);
            number = JSON.parse(number);
            ticketId = JSON.parse(ticketId);
            let timeDiff = date_fns_1.intervalToDuration({
                start: new Date(JSON.parse(messageDateTime)),
                end: new Date()
            });
            console.log("______timeDiff: ", timeDiff);
            if (timeDiff.seconds > 50) {
                RedisClient_1.del(`remote:ticketId:${ticketId}`);
                obj = yield controllByNumber_1.default();
                const io = socket_1.getIO();
                io.emit("remoteTickesControll", {
                    action: "update",
                    tickets: obj.ticketIds
                });
            }
        }
    }
    catch (error) {
        console.log("There was an error on auto remote tickets service: ", error);
    }
});
const schedule = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        clearInterval(timer);
        yield AutoRemoteTickets();
    }
    catch (error) {
        console.log("error on schedule: ", error);
    }
    finally {
        timer = setInterval(schedule, 5000);
    }
});
timer = setInterval(schedule, 5000);
exports.default = schedule;
