import { MatrixClient } from 'matrix-js-sdk';
import { EMOJI_REG_G, JUMBO_EMOJI_REG } from '../../../utils/regex';
import { trimReplyFromBody } from '../../../utils/room';
import { emojis } from '../../../plugins/emoji';
import { EMOJI_CONFETTI_EVENT_TYPE, EmojiConfettiContent } from './types';

const SHORTCODE_PATTERN = /:([^\s:]+):/g;

export function extractJumboEmojis(body: string): string[] {
  const trimmedBody = trimReplyFromBody(body).trim();
  if (!JUMBO_EMOJI_REG.test(trimmedBody)) return [];

  const found: string[] = [];

  for (const match of trimmedBody.matchAll(EMOJI_REG_G)) {
    const emoji = match[1];
    if (emoji) found.push(emoji);
  }

  for (const match of trimmedBody.matchAll(SHORTCODE_PATTERN)) {
    const shortcode = match[1];
    const resolved = emojis.find((emoji) => emoji.shortcode === shortcode);
    if (resolved) found.push(resolved.unicode);
  }

  return found.length > 0 ? found : ['🎉'];
}

export function sendEmojiConfettiEvent(
  mx: MatrixClient,
  roomId: string,
  targetEventId: string,
  emojis: string[]
) {
  const content: EmojiConfettiContent = {
    emojis,
    msgtype: EMOJI_CONFETTI_EVENT_TYPE,
    target_event_id: targetEventId,
  };

  return mx.sendEvent(roomId, EMOJI_CONFETTI_EVENT_TYPE as never, content);
}
