import makeWASocket, {
  DisconnectReason,
  useMultiFileAuthState,
} from "@whiskeysockets/baileys";
import { Boom } from "@hapi/boom";
import { Request, RequestHandler, Response } from "express";
import qr from "qr-image";

const session = new Map();
const VAR = "VAR_SESSION";
let connectionStatus: string = "Sedang cek koneksi";
let qrCode: string;

export const initWhatsapp = async () => {
  await connectToWhatsApp();
};

export const getStatus: RequestHandler = async (
  req: Request,
  res: Response
) => {
  if (qrCode == null || qrCode == undefined) {
    res.json({
      success: true,
      data: connectionStatus,
      message: "Sukses menampilkan status",
    });
  } else {
    const code = qr.image(qrCode, { type: "png" });
    res.setHeader("Content-type", "image/png");
    code.pipe(res);
  }
};

export const sendMessage: RequestHandler = async (
  req: Request,
  res: Response
) => {
  const { nama, whatsapp } = req.body;
  const wa = whatsapp[0];
  const waReplaced = whatsapp.replace(wa, "62");

  const msgClient = `Halo Bapak/Ibu ${nama}\n\nTerima kasih sudah mengisi formulir yang telah disediakan`;
  await session
    .get(VAR)
    .sendMessage(`${waReplaced}@s.whatsapp.net`, { text: msgClient });

  res.json({
    success: true,
    data: `Halo ${nama} dengan nomor ${waReplaced}`,
    message: "Sukses",
  });
};

async function connectToWhatsApp() {
  const { state, saveCreds } = await useMultiFileAuthState("auth");
  const sock = makeWASocket({
    // can provide additional config here
    printQRInTerminal: true,
    auth: state,
  });
  sock.ev.on("creds.update", saveCreds);
  sock.ev.on("connection.update", (update) => {
    const { connection, lastDisconnect } = update;
    if (update.qr) {
      qrCode = update.qr;
    }
    if (connection === "close") {
      const shouldReconnect =
        (lastDisconnect?.error as Boom)?.output?.statusCode !==
        DisconnectReason.loggedOut;
      console.log(
        "connection closed due to ",
        lastDisconnect?.error,
        ", reconnecting ",
        shouldReconnect
      );
      // reconnect if not logged out
      connectionStatus = "closed";
      if (shouldReconnect) {
        connectToWhatsApp();
      }
    } else if (connection === "open") {
      connectionStatus = "connected";
      console.log("opened connection");
    }
  });
  sock.ev.on("messages.upsert", async (m) => {
    const msg = m.messages[0];
    const noHp: string = msg.key.remoteJid!;
    const nama = msg.pushName;
    if (!msg.key.fromMe && m.type === "notify") {
      if (noHp.includes("@s.whatsapp.net")) {
        if (msg.message?.conversation == "1") {
          await sock.sendMessage(noHp, {
            text: "Silahkan mengisi formulir *Pendaftaran Warga Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/GnGSzAj2Lx5Gpuvx5",
          });
        } else if (msg.message?.conversation == "2") {
          await sock.sendMessage(noHp, {
            text: "Silahkan mengisi formulir *Lapor NOP Warga Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/uELxaUufGC3nwGYr5",
          });
        } else if (msg.message?.conversation == "3") {
          await sock.sendMessage(noHp, {
            text: "Silahkan mengisi formulir *Pendaftaran Milenial Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/uc1Te6jZ7UQDmSYP9",
          });
        } else if (msg.message?.conversation == "4") {
          await sock.sendMessage(noHp, {
            text: "Silahkan mengisi formulir *Lapor NOP Milenial Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/T4RWm3zqUpCKpXw3A",
          });
        } else {
          await sock.sendMessage(noHp, {
            text: `Halo Bapak/Ibu ${nama}, perkenalkan Saya Bot Pintar, asisten pribadi Bapenda Kab. Bojonegoro \n\nSilahkan balas dengan angka sesuai opsi menu yang Sahabat inginkan \n1. Pendaftaran Warga Agen Pajak \n2. Lapor Nop Warga Agen Pajak \n3. Pendaftaran Milenial Agen Pajak \n4. Lapor NOP Milenial Agen Pajak \n\nSilahkan pilih sesuai kategori, jika Anda *Warga Negara Indonesia (Non Pelajar/Mahasiswa)* pilih kategori *Warga Agen Pajak*, tetapi jika Anda *Pelajar/Mahasiswa* silahkan pilih kategori *Milenial Agen Pajak*`,
          });
        }
      }
    }
  });

  session.set(VAR, sock);
}
