import path from "path";
import autoRestore from "../../helpers/AutoRestore";
import { removeDir } from "../../helpers/DeleteDirectory";
import { delRestoreControllFile, getRestoreControll } from "../../helpers/RestoreControll";
// import { insertOrUpeateWhatsCache, loadWhatsappCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import { getIO } from "../../libs/socket";
import Whatsapp from "../../models/Whatsapp";
import ListWhatsAppsService from "../WhatsappService/ListWhatsAppsService";
import { StartWhatsAppSession } from "./StartWhatsAppSession";
const fs = require('fs')

import "../../helpers/SchedulingNotifySendMessage"
import "../../helpers/WhoIsOnlineMonitor"

import { cacheSize, flushCache, loadTicketsCache } from "../../helpers/TicketCache";
import { loadContactsCache } from "../../helpers/ContactsCache";
import { loadSchedulesCache } from "../../helpers/SchedulingNotifyCache";
import { createSessionDir } from "../../helpers/CreateSessionDir";

import openSocket from "socket.io-client";


let counter = 0

export const StartAllWhatsAppsSessions = async (): Promise<void> => {
  

  const cacheLength = await cacheSize()

  console.log('cacheSize: ', cacheLength)

  if (cacheLength == 0) {
    console.log('Loading from cache...')
    await flushCache()
    await loadContactsCache()
    await loadTicketsCache()
  }

  await loadSchedulesCache()
  // await loadWhatsappCache()


  createSessionDir()
  delRestoreControllFile()

  const whatsapps = await ListWhatsAppsService();

  if (whatsapps.length > 0) {

    whatsapps.forEach(async whatsapp => {

      // StartWhatsAppSession(whatsapp); 

      const sourcePath = path.join(process.cwd(), `.wwebjs_auth/`, `session-bd_${whatsapp.id}`)

      if (fs.existsSync(sourcePath)) {

        await removeDir(sourcePath)

        console.log('Directory deleted on start process: ', sourcePath)
      }
      else {
        console.log('Directory not found to delete on start process: ', sourcePath)
      }

      await whatsapp.update({ status: "RESTORING" });
      // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
      //   status: "RESTORING",
      // })

      const io = getIO();
      io.emit("whatsappSession", {
        action: "update",
        session: whatsapp
      });

      console.log('1 counter: ', counter)

      setTimeout(async () => {

        let whats: any = await Whatsapp.findOne({ where: { id: whatsapp.id } });

        if (whats && whats.status !== 'CONNECTED') {

          let lstRestore = getRestoreControll()

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

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

            console.log(` EXECUTING RESTORING ON whatsappId: ${whatsapp.id}`)

          } else {

            await autoRestore(whatsapp.id,)

          }


        }


      }, counter)



      counter += 57000

    });

  }


};
