import * as React from 'react';
import videojs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js';
// import 'videojs-contrib-dash';
import { ResponsiveEmbed } from 'react-bootstrap';

export default class VideoPlayer extends React.Component<{
  onReady?: () => void,
  onVolumeChange?: (e: Event) => void,
  onTimeUpdate?: (e: Event) => void,
} & VideoJsPlayerOptions> {
  videoNode: HTMLVideoElement;

  player: VideoJsPlayer;

  componentDidMount() {
    const {
      onReady,
      onTimeUpdate,
      onVolumeChange,
      defaultVolume,
      ...videoJsOptions
    } = this.props;
    this.player = videojs(this.videoNode, videoJsOptions, onReady);
    if (typeof defaultVolume === 'number' && !Number.isNaN(defaultVolume)) {
      this.player.volume(defaultVolume);
    }
    if (onVolumeChange) { this.player.on('volumechange', onVolumeChange); }
    if (onTimeUpdate) { this.player.on('timeupdate', onTimeUpdate); }
  }

  componentWillUnmount() {
    if (this.player) {
      this.player.dispose();
    }
  }

  render() {
    const {
      sources,
      controls,
      autoplay,
      onReady,
      ...videoJsOptions
    } = this.props;
    return (
      <ResponsiveEmbed aspectRatio="16by9">
        <div>
          <div data-vjs-player>
            {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
            <video
              ref={(node) => { this.videoNode = node; }}
              className="video-js"
              data-setup={
                JSON.stringify({
                  autoplay,
                  controls,
                  ...videoJsOptions,
                })
              }
              controls={controls}
              autoPlay={!!(autoplay === 'true' || autoplay === true)}
            >
              {sources.map(
                ({ src, type }) => (
                  <source
                    key={`${JSON.stringify({ src, type })}`}
                    src={src}
                    type={type}
                  />
                ),
              )}
              <p className="vjs-no-js">
                {/* TODO - localize */}
                To view this video please enable JavaScript, and consider upgrading to a
                web browser that
                <a href="https://videojs.com/html5-video-support/" target="_blank" rel="noreferrer">
                  supports HTML5 video
                </a>
              </p>
            </video>
          </div>
        </div>
      </ResponsiveEmbed>
    );
  }
}
