const { generateWAMessageFromContent, generateWAMessage, downloadContentFromMessage } = require("@whiskeysockets/baileys")
const fs = require('fs')
const crypto = require('crypto')
const FileType = require('file-type');    

module.exports = async (depayy) => {

    depayy.ev.on('group-participants.update', async (update) => {
        const { id, author, participants, action } = update;
        try {
            global.db = global.db || {};
            global.db.groups = global.db.groups || {};
            global.db.groups[id] = global.db.groups[id] || { welcome: true };
            if (!global.db.groups[id].welcome) return;
            const metadata = await depayy.groupMetadata(id);
            for (let n of participants) {
                let teks = "";
                const user = `@${n.split('@')[0]}`;
                const pelaku = author ? `@${author.split('@')[0]}` : "Sistem";
                if (action === 'add') {
                    teks = !author ? `Selamat datang ${user} di grup ${metadata.subject}. Harap membaca deskripsi grup sebelum berinteraksi.` : `${pelaku} telah menambahkan ${user}. Beban grup sekarang bertambah satu.`;
                } else if (action === 'remove') {
                    teks = author === n ? `${user} telah keluar dari grup sekarang beban grup sudah berkurang satu.` : `${user} telah dikeluarkan oleh ${pelaku}. Sekarang beban grup telah musnah satu dari grup`;
                } else if (action === 'promote') {
                    teks = `${user} telah diangkat menjadi admin oleh ${pelaku}.`;
                } else if (action === 'demote') {
                    teks = `${user} telah diturunkan dari jabatan admin oleh ${pelaku}.`;
                }
                if (!teks) continue;
                await depayy.sendMessage(id, { text: teks, contextInfo: { mentionedJid: author ? [author, n] : [n] } }, { quoted: { key: { fromMe: false, participant: '0@s.whatsapp.net', remoteJid: 'status@broadcast' }, message: { conversation: '⚝ ᗪΞᎮᗑƔ - OFFC' } } });
            }
        } catch (err) { console.log("Group Update Error:", err) }
    });


    depayy.sendText = async (jid, text, quoted = '', options) => {
        depayy.sendMessage(jid, { text: text, ...options }, { quoted });
    };

    depayy.downloadMediaMessage = async (message) => {
        let mime = (message.msg || message).mimetype || '';
        let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0];
        const stream = await downloadContentFromMessage(message, messageType);
        let buffer = Buffer.from([]);
        for await (const chunk of stream) { buffer = Buffer.concat([buffer, chunk]) }
        return buffer;
    };

   depayy.downloadAndSaveMediaMessage = async (message, filename, attachExtension = true) => {
        let quoted = message.msg ? message.msg : message;
        let mime = (message.msg || message).mimetype || "";
        let messageType = message.mtype ? message.mtype.replace(/Message/gi, "") : mime.split("/")[0];
        const stream = await downloadContentFromMessage(quoted, messageType);
        let buffer = Buffer.from([]);
        for await (const chunk of stream) { buffer = Buffer.concat([buffer, chunk]) }
        let type = await FileType.fromBuffer(buffer);
        let trueFileName = attachExtension ? filename + "." + type.ext : filename;
        await fs.writeFileSync(trueFileName, buffer);
        return trueFileName;
    };

    depayy.sendFile = async (jid, path, filename = '', caption = '', quoted, ptt = false, options = {}) => {
        let type = await depayy.getFile(path, true);
        let { res, data: file, filename: pathFile } = type;
        let opt = { filename };
        if (quoted) opt.quoted = quoted;
        let mtype = '', mimetype = type.mime;
        if (/webp/.test(type.mime)) mtype = 'sticker';
        else if (/image/.test(type.mime)) mtype = 'image';
        else if (/video/.test(type.mime)) mtype = 'video';
        else mtype = 'document';
        let message = { ...options, caption, ptt, [mtype]: { url: pathFile }, mimetype };
        return await depayy.sendMessage(jid, message, { ...opt, ...options });
    };

    depayy.albumMessage = async (jid, array, quoted) => {
        const album = generateWAMessageFromContent(jid, {
            messageContextInfo: { messageSecret: crypto.randomBytes(32) },
            albumMessage: {
                expectedImageCount: array.filter((a) => a.hasOwnProperty("image")).length,
                expectedVideoCount: array.filter((a) => a.hasOwnProperty("video")).length,
            },
        }, { userJid: depayy.user.jid, quoted, upload: depayy.waUploadToServer });
        await depayy.relayMessage(jid, album.message, { messageId: album.key.id });
        for (let content of array) {
            const img = await generateWAMessage(jid, content, { upload: depayy.waUploadToServer });
            img.message.messageContextInfo = {
                messageSecret: crypto.randomBytes(32),
                messageAssociation: { associationType: 1, parentMessageKey: album.key },
                participant: "0@s.whatsapp.net", remoteJid: "status@broadcast", isForwarded: true
            };
            await depayy.relayMessage(jid, img.message, { messageId: img.key.id, quoted: { key: album.key, message: album.message } });
        }
        return album;
    };

    depayy.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
        let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`, `[1], 'base64') : /^https?:\/\//.test(path) ? await (await require('axios').get(path, { responseType: 'arraybuffer' })).data : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0);
        let buffer = options && (options.packname || options.author) ? await writeExifImg(buff, options) : await addExif(buff);
        await depayy.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted });
        return buffer;
    };

    depayy.sendVideoAsSticker = async (jid, path, quoted, options = {}) => {
        let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`, `[1], 'base64') : /^https?:\/\//.test(path) ? await (await require('axios').get(path, { responseType: 'arraybuffer' })).data : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0);
        let buffer = options && (options.packname || options.author) ? await writeExifVid(buff, options) : await videoToWebp(buff);
        await depayy.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted });
        return buffer;
    };

    depayy.sendStatusMention = async (content, jids = []) => {
        let users;
        for (let id of jids) {
            let userId = await depayy.groupMetadata(id);
            users = await userId.participants.map(u => depayy.decodeJid(u.id));
        };
        let message = await depayy.sendMessage("status@broadcast", content, {
            backgroundColor: "#000000", font: Math.floor(Math.random() * 9), statusJidList: users,
            additionalNodes: [{ tag: "meta", attrs: {}, content: [{ tag: "mentioned_users", attrs: {}, content: jids.map((jid) => ({ tag: "to", attrs: { jid }, content: undefined })) }] }]
        });
        jids.forEach(id => {
            depayy.relayMessage(id, { groupStatusMentionMessage: { message: { protocolMessage: { key: message.key, type: 25 } } } }, { userJid: depayy.user.jid, additionalNodes: [{ tag: "meta", attrs: { is_status_mention: "true" }, content: undefined }] });
        });
        return message;
    };

    return depayy
}

