import WaveSurfer from 'wavesurfer.js';

export interface AudioMetadata {
  duration?: number;
}

export const getAudioMetadata = (audioUrl?: string, fileType?: string) => new Promise<AudioMetadata>(async (resolve, reject) => {
  // TODO server side
  if (fileType === 'audio/mid') {
    resolve({});
    return;
  }

  try {
    const dummyContainer = window.document.createElement('div');
    const waveSurferInstance = WaveSurfer.create({
      container: dummyContainer,
    });

    waveSurferInstance.on('ready', async () => {
      const metadata = {
        duration: waveSurferInstance.getDuration(),
      };

      waveSurferInstance.destroy();
      dummyContainer.remove();
      resolve(metadata);
    });

    if (audioUrl === undefined) {
      resolve({});
      return;
    }

    await waveSurferInstance.load(audioUrl);
  } catch (err) {
    reject(err);
  }
});
