import {data} from "../wwwroot/core/appData.js";
import {launchWorker} from "../wwwroot/core/namecards/workerLauncher.js";
import {AttachmentBuilder} from "discord.js";
import {Logger} from "../wwwroot/core/logging/logger.js";
import StringFormatter from "../wwwroot/core/utils/stringFormatter.js";

data.client.on('clientReady', async () => {
    console.log("Ready!");

    const guild = await data.client.guilds.fetch(data.testGuildID);
    const member = await guild.members.fetch(data.testUserID);

    console.log("Emitting fake guildMemberAdd...");
    data.client.emit("guildMemberAdd", member);
});

data.client.on('guildMemberAdd', async (member) => {
    const possibleMessages = [
        "<@:user> is one of us!",
        "I know what you are, <@:user>...",
        "Osmanthus wine tastes the same as I— oop, wrong line <@:user>",
        "Yeah yeah, welcome or whatever <@:user>",
        "OH. MY. GOD Y'ALL— <@:user> is here!",
        "So... we're all seeing <@:user, right?>",
        "<@:user> is right behind me, aren't they...?"
    ]
    const choseMessage = possibleMessages[Math.floor(Math.random() * possibleMessages.length)];

    try {
        const avatarUrl = member.user.displayAvatarURL({ extension: 'png', size: 512 });
        const username = member.displayName || member.user.username;

        const result = await launchWorker({
            templatePath: data.nameCardTemplate,
            avatarURL: avatarUrl,
            username: username,
        });

        const attachment = new AttachmentBuilder(Buffer.from(result.result), { name: 'namecard.png' });

        const channel = await member.guild.channels.fetch(data.welcomeChannelID);
        await channel.send({
            content: StringFormatter.format(choseMessage, [ {key : "user", value : member.id} ]),
            allowedMentions: {
                users: [member.id]
            },
            files: [attachment]
        });

    } catch (err) {
        await Logger.error('Failed to generate/send name card:', err);
    }
});

await data.client.login(process.env.DISCORD_TOKEN);
