import { P2P_BASE64_CHUNK_SIZE_BYTES } from './p2p-transfer.constants';

export function arrayBufferToBase64(buffer: ArrayBuffer): string {
  let binary = '';

  const bytes = new Uint8Array(buffer);

  for (let index = 0; index < bytes.byteLength; index++) {
    binary += String.fromCharCode(bytes[index]);
  }

  return btoa(binary);
}

export function decodeBase64(base64: string): Uint8Array {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);

  for (let index = 0; index < binary.length; index++) {
    bytes[index] = binary.charCodeAt(index);
  }

  return bytes;
}

export async function* iterateBlobChunks(
  blob: Blob,
  chunkSize = P2P_BASE64_CHUNK_SIZE_BYTES
): AsyncGenerator<{ base64: string; index: number; total: number }, void, undefined> {
  const totalChunks = Math.ceil(blob.size / chunkSize);

  let offset = 0;
  let chunkIndex = 0;

  while (offset < blob.size) {
    const slice = blob.slice(offset, offset + chunkSize);
    const arrayBuffer = await slice.arrayBuffer();

    yield {
      base64: arrayBufferToBase64(arrayBuffer),
      index: chunkIndex,
      total: totalChunks
    };

    offset += chunkSize;
    chunkIndex++;
  }
}
