import { writeFile, readFile } from 'fs';
import { execSync } from 'child_process';
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { Lame } from 'node-lame';
import tmp from 'tmp';

const s3 = new S3Client({ region: 'us-east-1' });

const convertFile = async (key: string) => {
  const inputFileExtension = key.split('.').pop();
  const outputFileKey = key.replace(inputFileExtension, 'mp3');

  const inputFileURL = await getSignedUrl(s3, new GetObjectCommand({
    Key: key,
    Bucket: 'samples-test-1',
  }));

  const file = new DataView((await (await fetch(inputFileURL)).arrayBuffer()));

  await new Promise<void>((resolve, reject) => {
    tmp.file(async (err, path, fd, cleanupCallback) => {
      const inputFilePath = `${path}.${inputFileExtension}`;
      const outputFilePath = `${path}.mp3`;
      writeFile(inputFilePath, file, async (err) => {
        if (err) {
          throw err;
        }

        const encoder = new Lame({
          output: outputFilePath,
          vbr: true,
          "vbr-quality": 3
        }).setFile(inputFilePath);

        await encoder.encode();

        readFile(outputFilePath, async (err, mp3File) => {
          if (err) {
            throw err;
          }

          await s3.send(
            new PutObjectCommand({
              Bucket: 'samples-test-1',
              Key: outputFileKey,
              Body: mp3File,
            })
          );

          console.log(await getSignedUrl(s3, new GetObjectCommand({
            Key: outputFileKey,
            Bucket: 'samples-test-1',
          })));

          cleanupCallback();

          resolve();
        });
      });
    });
  });
};

// await convertFile('Salamander Piano Micro (sampled by Alexander Holm)/C1v1-aac6d925-9e72-4aba-9d15-d0b782c33879.wav');
