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

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

  const { spaceIdOrAlias: rawSpaceIdOrAlias } = useParams();
  const spaceIdOrAlias = decodeRouteParam(rawSpaceIdOrAlias);

  const spaceId =
    spaceIdOrAlias && isRoomAlias(spaceIdOrAlias)
      ? getCanonicalAliasRoomId(mx, spaceIdOrAlias)
      : spaceIdOrAlias;

  return spaceId;
};

/** True when the current URL is the forum feed route. */
export const useSpaceFeedSelected = (): boolean => {
  const { pathname } = useLocation();
  return /\/feed\/?$/.test(pathname);
};

export const useSpaceLobbySelected = (_spaceIdOrAlias?: string): boolean => {
  const { pathname } = useLocation();
  return /\/lobby\/?$/.test(pathname);
};

export const useSpaceSearchSelected = (_spaceIdOrAlias?: string): boolean => {
  const { pathname } = useLocation();
  return /\/search\/?$/.test(pathname);
};
