import {VideoMetadata} from './common';

export const getMetadataFromUrl = async (videoUrl: string) => new Promise<Partial<VideoMetadata>>((resolve, reject) => {
  const video = window.document.createElement('video');
  const source = window.document.createElement('source');

  video.addEventListener('loadedmetadata', (videoLoadEvent) => {
    const thisVideo = videoLoadEvent.currentTarget as HTMLVideoElement;
    const metadata = {
      width: thisVideo.videoWidth,
      height: thisVideo.videoHeight,
      duration: thisVideo.duration,
    };
    video.remove();
    resolve(metadata);
  });

  video.addEventListener('error', () => {
    reject(new Error('Could not load file as video'));
    video.remove();
  });

  source.src = videoUrl;
  video.appendChild(source);
});
