import gracefulShutdown from "http-graceful-shutdown";
import app from "./app";
import { initIO, getIO } from "./libs/socket";
import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
import User from "./models/User";
import Whatsapp from "./models/Whatsapp";
import endPointQuery from "./helpers/EndPointQuery";
import {
  cacheSize,
  flushCache,
  loadTicketsCache,  
} from "./helpers/TicketCache";

import "./helpers/CloseBotTickets";
import { loadContactsCache } from "./helpers/ContactsCache";
import { loadSchedulesCache } from "./helpers/SchedulingNotifyCache";
import { delRestoreControllFile } from "./helpers/RestoreControll";
import "./helpers/AutoCloseTickets";
import "./helpers/AutoRemoteTickets";

import "./helpers/SchedulingNotifySendMessage";
import axios from "axios";
import os from "os";
import Setting from "./models/Setting";

import fs from "fs";
import dir from "path";
import { getSettingValue } from "./helpers/WhaticketSettings";
import loadSettings from "./helpers/LoadSettings";
import { clearAllKeys, get, set } from "./helpers/RedisClient";
import ShowUserService from "./services/UserServices/ShowUserService";
import { json } from "sequelize";
import { setBotInfo } from "./helpers/SetBotInfo";
import Queue from "./models/Queue";
import StatusChatEnd from "./models/StatusChatEnd";
import Message from "./models/Message";

const server = app.listen(process.env.PORT, () => {
  logger.info(`Server started on port: ${process.env.PORT}`);
});

// if (global.gc) {
//   console.log(">> Starting Garbage Collector...");
//   global.gc();
// } else {
//   console.warn('No GC hook! Start your program as `node --expose-gc file.js`.');
// }

initIO(server);

// StartAllWhatsAppsSessions();
gracefulShutdown(server);

(async () => {
  console.log("os.tmpdir(): ", os.tmpdir());

  await clearAllKeys(
    "user:*",
    "whatsapp:*",
    "queue:*",
    "statusChatEnd:*", 
  ); 
  
  // let messages: any = await Message.findAll({
  //   attributes: ["id", "ticketId", "body"]
  // });

  // for (const message of messages) {
  //   const { id, body, ticketId } = message;
  //   await set(`message:ticketId:${ticketId}:id:${id}`, body);
  // }

  const statusChatEnds = await StatusChatEnd.findAll();

  for (const statusChatEnd of statusChatEnds) {
    const { id, name, farewellMessage } = statusChatEnd;
    await set(`statusChatEnd:${id}`, { id, name, farewellMessage });
  }

  const users = await User.findAll();

  for (const user of users) {
    const { id, name } = user;

    if (name == "botqueue") {
      const userService = await ShowUserService(id);
      await setBotInfo(userService);
    }

    await set(`user:${id}`, { id, name });
  }

  const queues = await Queue.findAll();

  for (const queue of queues) {
    const { id, greetingMessage, name, farewellMessage } = queue;
    await set(`queue:${id}`, { id, name, greetingMessage, farewellMessage });
  }

  loadSettings();

  let whatsapps: any = await Whatsapp.findAll({
    attributes: ["id", "url", "phoneNumberId", "number", "greetingMessage"]
  });

  if (whatsapps && whatsapps.length > 0) {
    for (let i = 0; i < whatsapps.length; i++) {
      try {
        const { phoneNumberId, id, greetingMessage } = whatsapps[i];

        // if (phoneNumberId) {
        //   await set(
        //     `whatsapp:${whatsapps[i].dataValues.id}`,
        //     JSON.stringify({
        //       number: whatsapps[i].dataValues.number,
        //       id,
        //       greetingMessage,
        //       phoneNumberId
        //     })
        //   );
        // }

        await set(
          `whatsapp:${whatsapps[i].dataValues.id}`,
          JSON.stringify({
            number: whatsapps[i].dataValues.number,
            id,
            greetingMessage,
            phoneNumberId
          })
        );

        if (phoneNumberId) {
          continue;
        }

        console.log(
          `API URL: ${whatsapps[i].dataValues.url}/api/connection/status`
        );

        const response = await axios.get(
          `${whatsapps[i].dataValues.url}/api/connection/status`,
          {}
        );

        console.log(`-------> Response: ${response.data.data}`);

        if (!response) {
          throw new Error("Response null");
        }

        if (response.data.data && response.data.data == "CONNECTED") {
          await whatsapps[i].update({ status: "CONNECTED" });
        }
      } catch (error: any) {
        await whatsapps[i].update({ status: "OPENING" });

        console.log(
          `There was an error on try acess the api sessions ${whatsapps[i].dataValues.url}`
        );
      }

      await new Promise(f => setTimeout(f, 100));
    }
  }

  if (process.env.CACHE) {
    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()
  }

  delRestoreControllFile();
})();

setTimeout(async () => {
  const io = getIO();

  console.log("Triggered socket!");

  let users = await User.findAll({ raw: true, attributes: ["id"] });

  if (users && users.length > 0) {
    for (let i = 0; i < users.length; i++) {
      io.emit("reload_page", {
        action: "update",
        userId: users[i].id
      });

      console.log("USER ID: ", users[i].id);

      await new Promise(f => setTimeout(f, 100));
    }
  }
}, 5000);
