"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.stopWhoIsOnlineMonitor = exports.startWhoIsOnlineMonitor = exports.WhoIsOnlineMonitor = void 0;
const socket_1 = require("../libs/socket");
const CreateOrUpdateOnlineUserService_1 = __importDefault(require("../services/UserServices/CreateOrUpdateOnlineUserService"));
const SplitDateTime_1 = require("../helpers/SplitDateTime");
const format_1 = __importDefault(require("date-fns/format"));
const pt_BR_1 = __importDefault(require("date-fns/locale/pt-BR"));
const SumOlineTimeNow_1 = __importDefault(require("../helpers/SumOlineTimeNow"));
let _fifo;
let whoIsOnline_monitor;
// const listUserId:any[] = [{'id':8, status: 'offline'},{'id':3,  status: 'offline'},{'id':5,  status: 'offline'}] 
let listUserId = [];
let count = 0;
// let countTest = 0
let uuid = 0;
let dateTime = SplitDateTime_1.splitDateTime(new Date(format_1.default(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: pt_BR_1.default })));
let timeInterval = 5;
let lstOnline = [];
let deleted = false;
const emitterOnline = (user, status, showOnlineTime = true) => {
    if (!user.id || !user.updatedAt || !user.onlineTime)
        return;
    let newOnlinetime = SumOlineTimeNow_1.default(user);
    let onlineTime = {
        userId: user.id,
        status: status,
        onlineTime: newOnlinetime,
    };
    if (!showOnlineTime) {
        onlineTime = {
            userId: user.id,
            status: status
        };
    }
    // console.log('-------------> onlineTime: ', onlineTime)
    const io = socket_1.getIO();
    io.emit("onlineStatus", {
        action: "update",
        userOnlineTime: onlineTime
    });
};
const monitor = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const usersSocket = require('./../libs/socket');
        if (usersSocket === null || usersSocket === void 0 ? void 0 : usersSocket.ob) {
            if (count > 1) {
                count = 0;
            }
            if (count == 0) {
                uuid = usersSocket.ob.uuid;
            }
            if (count == 1) {
                if (uuid) {
                    if (uuid == usersSocket.ob.uuid) {
                        console.log('ALL USERS CLIENTS OFFLINE 1...........');
                        usersSocket.ob.listOnline = [];
                        usersSocket.ob.listOnlineAux = [];
                        usersSocket.ob.uuid = undefined;
                    }
                }
            }
            else {
                usersSocket.ob.listOnline.forEach((el) => __awaiter(void 0, void 0, void 0, function* () {
                    const indexAux = lstOnline.findIndex((e) => e.id == el.id);
                    if (indexAux == -1) {
                        const userOnline = yield CreateOrUpdateOnlineUserService_1.default({ userId: el.id, status: 'online' });
                        if (userOnline) {
                            el.onlineTime = userOnline.onlineTime;
                            el.updatedAt = userOnline.updatedAt,
                                console.log('    *        CREATED OR UPDATED USER TO ONLINE: ', userOnline.userId);
                            lstOnline.push({ 'id': el.id, 'status': 'online' });
                        }
                    }
                    // console.log('el: ', el)
                    if (el.status == 'waiting...') {
                        emitterOnline(el, el.status, false);
                    }
                    // else {
                    //     emitterOnline(el, el.status)
                    // }
                }));
                let difference = lstOnline.filter((x) => !usersSocket.ob.listOnline.map((e) => e.id).includes(x.id));
                difference.forEach((e) => __awaiter(void 0, void 0, void 0, function* () {
                    const index = lstOnline.findIndex((x) => x.id == e.id);
                    if (index != -1) {
                        lstOnline.splice(index, 1);
                        const userOnline = yield CreateOrUpdateOnlineUserService_1.default({ userId: e.id, status: 'offline' });
                    }
                }));
            }
            count++;
        }
    }
    catch (error) {
        console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ', error);
        listUserId = [];
        count = 0;
        // countTest = 0
        uuid = 0;
    }
});
const WhoIsOnlineMonitor = () => __awaiter(void 0, void 0, void 0, function* () {
    try {
        clearInterval(_fifo);
        yield monitor();
    }
    catch (error) {
        console.log('error on WhoIsOnlineMonitor: ', error);
    }
    finally {
        _fifo = setInterval(WhoIsOnlineMonitor, 3000);
    }
});
exports.WhoIsOnlineMonitor = WhoIsOnlineMonitor;
_fifo = setInterval(WhoIsOnlineMonitor, 3000);
const startWhoIsOnlineMonitor = (mileseconds) => __awaiter(void 0, void 0, void 0, function* () {
    listUserId = [];
    count = 0;
    // countTest = 0
    uuid = 0;
    clearInterval(_fifo);
    _fifo = setInterval(WhoIsOnlineMonitor, 3000);
    // if (mileseconds) {
    //     timeInterval = mileseconds
    // } 
});
exports.startWhoIsOnlineMonitor = startWhoIsOnlineMonitor;
const stopWhoIsOnlineMonitor = () => __awaiter(void 0, void 0, void 0, function* () {
    clearInterval(_fifo);
    // _fifo = setInterval(WhoIsOnlineMonitor, 3000);
});
exports.stopWhoIsOnlineMonitor = stopWhoIsOnlineMonitor;
