import { Message } from "discord.js";
import { getRepository } from "typeorm";
import { RandomMessageReaction } from "@shared/db/entity/RandomMesssageReaction";
import { client } from "src/client";
import { Event, BotEventData, Plugin } from "src/model/plugin";

const timeout = (ms: number) => new Promise(r => setTimeout(r, ms));

@Plugin
export class RandomReact {
    @Event("message")
    async showHelp({ actionsDone }: BotEventData, msg: Message): Promise<void> {
        if(actionsDone)
            return;

        const repo = getRepository(RandomMessageReaction);

        const reactInfo = await repo.findOne({ where: { userId: msg.author.id } });

        if(!reactInfo)
            return;

        const emote = client.bot.emojis.resolve(reactInfo.reactionEmoteId);

        if(!emote)
            return;

        if(Math.random() < reactInfo.reactProbability) {
            await timeout(Math.random() * reactInfo.maxWaitMs);
            await msg.react(emote);
        }
    }
}