export interface VideoFileMetadata {
  width?: number;
  height?: number;
  duration?: number;
}

export const getVideoMetadata = (videoUrl?: string) => new Promise<VideoFileMetadata>((resolve, reject) => {
  // TODO server side
  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();
  });

  if (typeof videoUrl === 'undefined') {
    resolve({});
    return;
  }

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