import WaveSurfer from 'wavesurfer.js';
import { AudioMetadata } from './common';

export const getMetadataFromUrl = (audioUrl: string) => new Promise<Partial<AudioMetadata>>((resolve, reject) => {
  try {
    const dummyContainer = window.document.createElement('div');
    // TODO remove wavesurfer dependency
    const waveSurferInstance = WaveSurfer.create({
      container: dummyContainer,
    });

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

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

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