import { Devs } from "@utils/constants";
import definePlugin from "@utils/types";
import { MessageStore, SelectedChannelStore, UserStore } from "@webpack/common";
import { Message } from "discord-types/general";

export default definePlugin({
    name: "ShyTyping",
    description: "Prevents you from accidentally revealing that you're lurking in a channel",
    authors: [Devs.Sqaaakoi],

    patches: [
        {
            find: '"TypingStore"',
            replacement: {
                match: /(TYPING_START_LOCAL:)(\i)/,
                replace: "$1$self.wrap($2)"
            }
        }
    ],

    wrap(startTyping: ({ channelId }: { channelId: string; }) => void) {
        return (e: { channelId: string; }) => {
            return this.shouldStartTyping(e.channelId) && startTyping(e);
        };
    },

    shouldStartTyping(channelId: string): boolean {
        if (SelectedChannelStore.getVoiceChannelId() === channelId) return true;
        const meId = UserStore.getCurrentUser().id;
        const threshold = Date.now() - (5 * 60 * 1000);
        // discord-types and the MessageStore types are so wrong and cursed
        if ((MessageStore.getMessages(channelId)._array as Message[]).filter(m => m.author.id === meId && !(m as any)?.deleted).some(m => +m.timestamp > threshold)) return true;



        return false;
    }
});
