import Whatsapp from "../models/Whatsapp"
import autoRestore from "./AutoRestore"
import { getRestoreControll } from "./RestoreControll" 

let lstAutoRestore: any = [] 

// Delete a directory and its children 
export const restoreMonit = (whatsappId: string | number) => {

    return

    try {

        let lstRestore: any = getRestoreControll()

        console.log('ENTROU NO AUTO RESTORE..................................')

        if (Object.keys(lstRestore.filter((e: any) => +e.id == +whatsappId)).length) {

            console.log('Restore executed by human whatasappId: ', whatsappId)

        }
        else {

            lstAutoRestore.push({ 'whatsappId': +whatsappId })

            setTimeout(async () => {

                lstRestore = getRestoreControll()

                let count = lstAutoRestore.length

                for (let i = 0; i < count; i++) {

                    let autoR = lstAutoRestore.shift()

                    console.log('----------------> autoR: ', autoR)

                    if (autoR && autoR.whatsappId) {

                        if (Object.keys(lstRestore.filter((e: any) => +e.id == +autoR.whatsappId)).length) {

                            console.log(' EXECUTING RESTORING autoR: ', autoR)

                            continue
                        }

                        const _whatsapp = await Whatsapp.findOne({ where: { id: autoR.whatsappId } });

                        console.log('----------------> autoR exec after 180 seconds: ', autoR)

                        let whatsappStatus = ["CONFLICT",
                            "DEPRECATED_VERSION",
                            "OPENING",
                            "PAIRING",
                            "PROXYBLOCK",
                            "SMB_TOS_BLOCK",
                            "TIMEOUT",
                            "TOS_BLOCK",
                            "UNLAUNCHED",
                            "UNPAIRED",
                            "UNPAIRED_IDLE"]

                        if (_whatsapp?.status) {

                            if (whatsappStatus.includes(_whatsapp.status)) {

                                await autoRestore(autoR.whatsappId, 'auto_monit')

                            }

                        }

                    }

                }
 
            }, 180000);

        }

    } catch (error) {
        console.log('There was an error on try execute AUTO-RESTORE: ', error)
    }

}