import * as Sentry from "@sentry/node";
import { Client } from "whatsapp-web.js";
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";

import { getIO } from "../../libs/socket";
import Whatsapp from "../../models/Whatsapp";
import { logger } from "../../utils/logger";
import { StartWhatsAppSession } from "./StartWhatsAppSession";





import { getRestoreControll, setRestoreControll, shifRestoreControll } from "../../helpers/RestoreControll";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";

import dir from 'path';

import autoRestore from "../../helpers/AutoRestore";
import { creationTime } from "../../helpers/CreationTime";
import { splitDateTime } from "../../helpers/SplitDateTime";

import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import path from "path";
import { restoreMonit } from "../../helpers/RestoreMonit";
const fs = require('fs')


let lstAutoRestore: any = []

interface Session extends Client {
  id?: number;
}

const wbotMonitor = async (
  wbot: Session,
  whatsapp: Whatsapp
): Promise<void> => {
  const io = getIO();
  const sessionName = whatsapp.name;

  try {
    wbot.on("change_state", async newState => {
      logger.info(`Monitor session: ${sessionName}, ${newState}`);

      console.log('>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ', wbot.info["wid"]["user"]) 

      try {
        await whatsapp.update({ status: newState });
        // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: newState })
      } catch (err: any) {
        Sentry.captureException(err);
        logger.error(err);
      }
 
      io.emit("whatsappSession", {
        action: "update",
        session: whatsapp
      });
      
      restoreMonit(whatsapp.id)

    });

    wbot.on("change_battery", async batteryInfo => {
      const { battery, plugged } = batteryInfo;
      logger.info(
        `Battery session: ${sessionName} ${battery}% - Charging? ${plugged}`
      );

      try {
        await whatsapp.update({ battery, plugged });
      } catch (err: any) {
        Sentry.captureException(err);
        logger.error(err);
      }

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

    wbot.on("disconnected", async reason => {
      logger.info(`Disconnected session: ${sessionName}, reason: ${reason}`);
      try {

        await whatsapp.update({ status: "OPENING", session: "" });
        // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "OPENING", session: "" })
      } catch (err: any) {
        Sentry.captureException(err);
        logger.error(err);
      }

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

      setTimeout(() => StartWhatsAppSession(whatsapp), 2000);
    });
  } catch (err: any) {
    Sentry.captureException(err);
    logger.error(err);
  }
};

export default wbotMonitor;
