import React from 'react';
import {connect} from 'react-redux';
import VideoPlayer from "../components/VideoPlayer";
import { fetchVideoById } from '../utils/api';

class Video extends React.Component {

  constructor() {
    super();
    this.state = {
      currentVideo: null
    };
  }

  componentDidMount() {
    // get videoId from the URL
    const videoId = this.props.match.params.videoId;

    // if data for videoId is already part of allVideos, setState to currentVideo
    if (this.props.allVideos && this.props.allVideos.hasOwnProperty(videoId)) {
      const currentVideo = this.props.allVideos[videoId];
      this.setState({currentVideo: currentVideo});
    } else {
      
      // video is not part of allVideos, fetch it from the API
      fetchVideoById(videoId)
        .then(video => {
          this.setState({
            currentVideo: video
          });
        });
    }
  }

  render() {
    const video = this.state.currentVideo;
    return (
      <section>
        { video && 
          <VideoPlayer 
            id={ video.id }
            title={ video.title }
            date = { video.date }
            description={ video.description }
          /> 
        }
      </section>
    );
  }
}

const mapStateToProps = state => ({
  allVideos: state.videos.allVideos
});

export default connect(mapStateToProps)(Video);