import { MatrixEvent } from 'matrix-js-sdk';
import { useState, useCallback } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback';
import { getAccountData } from '../utils/room';

export function useAccountData(eventType: string): MatrixEvent | undefined {
  const mx = useMatrixClient();
  const [event, setEvent] = useState<MatrixEvent | undefined>(() => getAccountData(mx, eventType));

  useAccountDataCallback(
    mx,
    useCallback(
      (evt) => {
        if (evt.getType() === eventType) {
          setEvent(evt);
        }
      },
      [eventType, setEvent],
    ),
  );

  return event;
}
