
import e from "express";
import { bool, number } from "yup";
import { getIO } from "../libs/socket";
import Queue from "../models/Queue";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";

import createOrUpdateOnlineUserService from "../services/UserServices/CreateOrUpdateOnlineUserService";
import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
import { check } from "prettier";
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
import { date } from "faker";

import sumOnlineTimeNow from '../helpers/SumOlineTimeNow'
import UserOnlineTime from "../models/UserOnlineTime";

let _fifo: any

let whoIsOnline_monitor: any;
// const listUserId:any[] = [{'id':8, status: 'offline'},{'id':3,  status: 'offline'},{'id':5,  status: 'offline'}] 
let listUserId: any[] = []
let count = 0
// let countTest = 0
let uuid: any = 0
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let timeInterval = 5
let lstOnline: any = []
let deleted: boolean = false;



const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true) => {

    if (!user.id || !user.updatedAt || !user.onlineTime) return

    let newOnlinetime = sumOnlineTimeNow(user)

    let onlineTime: any = {
        userId: user.id,
        status: status,
        onlineTime: newOnlinetime,
    }

    if (!showOnlineTime) {
        onlineTime = {
            userId: user.id,
            status: status
        }
    }

    // console.log('-------------> onlineTime: ', onlineTime)

    const io = getIO();
    io.emit("onlineStatus", {
        action: "update",
        userOnlineTime: onlineTime
    });
}


const monitor = async () => {

    try {

        const usersSocket = require('./../libs/socket');

        if (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(async (el: any) => {


                    const indexAux = lstOnline.findIndex((e: any) => e.id == el.id)


                    if (indexAux == -1) {

                        const userOnline = await createOrUpdateOnlineUserService({ 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: any) => !usersSocket.ob.listOnline.map((e: any) => e.id).includes(x.id));

                difference.forEach(async (e: any) => {

                    const index = lstOnline.findIndex((x: any) => x.id == e.id)

                    if (index != -1) {

                        lstOnline.splice(index, 1)

                        const userOnline = await createOrUpdateOnlineUserService({ 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 = async () => {

    try {
        clearInterval(_fifo);

        await monitor()

    } catch (error) {
        console.log('error on WhoIsOnlineMonitor: ', error)
    }
    finally {
        _fifo = setInterval(WhoIsOnlineMonitor, 3000);
    }
}

_fifo = setInterval(WhoIsOnlineMonitor, 3000);



const startWhoIsOnlineMonitor = async (mileseconds?: number) => {

    listUserId = []
    count = 0
    // countTest = 0
    uuid = 0

    clearInterval(_fifo);
    _fifo = setInterval(WhoIsOnlineMonitor, 3000);

    // if (mileseconds) {
    //     timeInterval = mileseconds
    // } 
}


const stopWhoIsOnlineMonitor = async () => {

    clearInterval(_fifo);
    // _fifo = setInterval(WhoIsOnlineMonitor, 3000);

}




export { WhoIsOnlineMonitor, startWhoIsOnlineMonitor, stopWhoIsOnlineMonitor }








