/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
export const parseStreamIdFromStreamUri = (uri: string): string => {
  const indexOfQuestionMark = uri.indexOf('?');
  const parsedUri = uri?.split('/') || [];
  const [protocol, , domain] = parsedUri;
  const streamUriPrefix = protocol && domain ? `${protocol}//${domain}/` : '';

  return uri.substring(streamUriPrefix.length, indexOfQuestionMark > -1 ? indexOfQuestionMark : uri.length);
};

interface IStreamInfo {
  streamId?: string;
  capabilities?: string[];
}

export const parseStreamInfoFromStreamUri = (uri: string): IStreamInfo => {
  if (!uri) {
    return;
  }

  const streamId = parseStreamIdFromStreamUri(uri);
  const queryParams = [...new URLSearchParams(uri.split('?')[1])].reduce((accumulator, [key, value]) => {
    if (key === 'capabilities') {
      accumulator[key] = value?.split(',') || [];

      return accumulator;
    }

    accumulator[key] = value;

    return accumulator;
  }, {});

  return {
    ...queryParams,
    streamId
  };
};
