import { useEffect, useState } from 'react';
import { ClientEvent, MatrixClient, MatrixEvent } from 'matrix-js-sdk';
import { getRecentEmojis } from '../plugins/recent-emoji';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { IEmoji, loadEmojiData } from '../plugins/emoji';

export const useRecentEmoji = (mx: MatrixClient, limit?: number): IEmoji[] => {
  const [recentEmoji, setRecentEmoji] = useState(() => getRecentEmojis(mx, limit));

  // Recent emojis are resolved against the (now lazily loaded) emojibase data
  // via getRecentEmojis. Recompute once loadEmojiData has populated it so the
  // recent list fills in on first open.
  useEffect(() => {
    let alive = true;
    loadEmojiData()
      .then(() => {
        if (alive) setRecentEmoji(getRecentEmojis(mx, limit));
      })
      .catch(() => undefined);
    return () => {
      alive = false;
    };
  }, [mx, limit]);

  useEffect(() => {
    const handleAccountData = (event: MatrixEvent) => {
      if (event.getType() !== AccountDataEvent.ElementRecentEmoji) return;
      setRecentEmoji(getRecentEmojis(mx, limit));
    };

    mx.on(ClientEvent.AccountData, handleAccountData);
    return () => {
      mx.removeListener(ClientEvent.AccountData, handleAccountData);
    };
  }, [mx, limit]);

  return recentEmoji;
};
