import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient';
import { useMediaAuthentication } from './useMediaAuthentication';
import { useRoomMemberChange } from './useRoomMemberChange';
import { getMemberName } from '../utils/room';
import { mxcUrlToHttp } from '../utils/matrix';

export type MemberAvatar = {
  name: string;
  avatarUrl: string | undefined;
};

/**
 * Resolve a room member's display name and avatar http url, staying reactive to
 * that member's profile (name/avatar/membership) changes.
 *
 * Stays reactive to this member's profile (name/avatar/membership) changes via
 * the shared member-change store (one global listener for the whole app).
 */
export const useMemberAvatar = (
  room: Room,
  userId: string,
  width = 32,
  height = 32,
  resizeMethod = 'crop',
): MemberAvatar => {
  const mx = useMatrixClient();
  const useAuthentication = useMediaAuthentication();

  useRoomMemberChange(room.roomId, userId);

  const name = getMemberName(room, userId);
  const avatarMxc = room.getMember(userId)?.getMxcAvatarUrl();
  const avatarUrl = avatarMxc
    ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, width, height, resizeMethod) ?? undefined)
    : undefined;

  return { name, avatarUrl };
};
