import { useParams } from 'react-router-dom';
import { decodeRouteParam } from '../../pages/pathUtils';
import { getCanonicalAliasRoomId, isRoomAlias } from '../../utils/matrix';
import { useMatrixClient } from '../useMatrixClient';

export const useSelectedRoom = (): string | undefined => {
  const mx = useMatrixClient();

  const { roomIdOrAlias: rawRoomIdOrAlias } = useParams();
  const roomIdOrAlias = decodeRouteParam(rawRoomIdOrAlias);
  const roomId =
    roomIdOrAlias && isRoomAlias(roomIdOrAlias)
      ? getCanonicalAliasRoomId(mx, roomIdOrAlias)
      : roomIdOrAlias;

  return roomId;
};
