"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendMessage = exports.getStatus = exports.initWhatsapp = void 0;
const baileys_1 = __importStar(require("@whiskeysockets/baileys"));
const qr_image_1 = __importDefault(require("qr-image"));
const session = new Map();
const VAR = "VAR_SESSION";
let connectionStatus = "Sedang cek koneksi";
let qrCode;
const initWhatsapp = () => __awaiter(void 0, void 0, void 0, function* () {
    yield connectToWhatsApp();
});
exports.initWhatsapp = initWhatsapp;
const getStatus = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (qrCode == null || qrCode == undefined) {
        res.json({
            success: true,
            data: connectionStatus,
            message: "Sukses menampilkan status",
        });
    }
    else {
        const code = qr_image_1.default.image(qrCode, { type: "png" });
        res.setHeader("Content-type", "image/png");
        code.pipe(res);
    }
});
exports.getStatus = getStatus;
const sendMessage = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    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`;
    yield session
        .get(VAR)
        .sendMessage(`${waReplaced}@s.whatsapp.net`, { text: msgClient });
    res.json({
        success: true,
        data: `Halo ${nama} dengan nomor ${waReplaced}`,
        message: "Sukses",
    });
});
exports.sendMessage = sendMessage;
function connectToWhatsApp() {
    return __awaiter(this, void 0, void 0, function* () {
        const { state, saveCreds } = yield (0, baileys_1.useMultiFileAuthState)("auth");
        const sock = (0, baileys_1.default)({
            // can provide additional config here
            printQRInTerminal: true,
            auth: state,
        });
        sock.ev.on("creds.update", saveCreds);
        sock.ev.on("connection.update", (update) => {
            var _a, _b;
            const { connection, lastDisconnect } = update;
            if (update.qr) {
                qrCode = update.qr;
            }
            if (connection === "close") {
                const shouldReconnect = ((_b = (_a = lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.statusCode) !==
                    baileys_1.DisconnectReason.loggedOut;
                console.log("connection closed due to ", lastDisconnect === null || lastDisconnect === void 0 ? void 0 : 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", (m) => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c, _d;
            const msg = m.messages[0];
            const noHp = msg.key.remoteJid;
            const nama = msg.pushName;
            if (!msg.key.fromMe && m.type === "notify") {
                if (noHp.includes("@s.whatsapp.net")) {
                    if (((_a = msg.message) === null || _a === void 0 ? void 0 : _a.conversation) == "1") {
                        yield sock.sendMessage(noHp, {
                            text: "Silahkan mengisi formulir *Pendaftaran Warga Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/GnGSzAj2Lx5Gpuvx5",
                        });
                    }
                    else if (((_b = msg.message) === null || _b === void 0 ? void 0 : _b.conversation) == "2") {
                        yield sock.sendMessage(noHp, {
                            text: "Silahkan mengisi formulir *Lapor NOP Warga Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/uELxaUufGC3nwGYr5",
                        });
                    }
                    else if (((_c = msg.message) === null || _c === void 0 ? void 0 : _c.conversation) == "3") {
                        yield sock.sendMessage(noHp, {
                            text: "Silahkan mengisi formulir *Pendaftaran Milenial Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/uc1Te6jZ7UQDmSYP9",
                        });
                    }
                    else if (((_d = msg.message) === null || _d === void 0 ? void 0 : _d.conversation) == "4") {
                        yield sock.sendMessage(noHp, {
                            text: "Silahkan mengisi formulir *Lapor NOP Milenial Agen Pajak* melalui link berikut ini\n\nhttps://forms.gle/T4RWm3zqUpCKpXw3A",
                        });
                    }
                    else {
                        yield 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);
    });
}
