import { useMemo } from 'react';
import { useMatrixClient } from './useMatrixClient';

import { decodeRouteParam } from '../pages/pathUtils';
import { getCanonicalAliasRoomId, isRoomAlias } from '../utils/matrix';

export const useJoinedRoomId = (allRooms: string[], roomIdOrAlias: string): string | undefined => {
  const mx = useMatrixClient();

  const joinedRoomId = useMemo(() => {
    const decoded = decodeRouteParam(roomIdOrAlias) ?? roomIdOrAlias;
    const roomId = isRoomAlias(decoded)
      ? getCanonicalAliasRoomId(mx, decoded)
      : decoded;

    if (roomId && allRooms.includes(roomId)) return roomId;
    return undefined;
  }, [mx, allRooms, roomIdOrAlias]);

  return joinedRoomId;
};
