import StreamSaver from 'streamsaver';
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';


async function downloadFile(client: S3Client, bucket: string, key: string, filename: string) {
  let command = new GetObjectCommand({
    Bucket: bucket,
    Key: key,
  });

  const data = await client.send(command);

  console.log("body:", data.Body);

  const fileStream = StreamSaver.createWriteStream(filename);
  const writer = fileStream.getWriter();

  const reader = (data.Body! as ReadableStream).getReader();

  const pump = (): Promise<null|undefined> => reader.read()
    .then(({ value, done }) => {
      if (done) writer.close();
      else {
        writer.write(value);
        return writer.ready.then(pump);
      }
    });

  await pump()
    .then(() => console.log('Closed the stream, Done writing'))
    .catch(err => console.log(err));
}

export default downloadFile;
