import React from 'react';
import {getVideo} from '../utils/video';
import {Player} from 'video-react';
import RelatedVideos from "./RelatedVideos";
import {getAllTopics, getRandomTopicVideos} from "../actions/topics";
import connect from "react-redux/es/connect/connect";

class VideoPlayer extends React.Component {
  componentDidMount() {
    if (this.props.allTopics && this.props.allTopics.length > 0 && !this.props.randomTopic) {
      this.props.getRandomTopicVideos(this.props.allTopics);
    } else {
      this.props.getAllTopics();
    }
  }

  componentWillReceiveProps(nextProps) {
    // This is slightly awkward - we need to check that we have all topics,
    // But don't have a random topic yet (or at not already loading a random topic)
    if ((this.props.allTopics || nextProps.allTopics) && !this.props.loadingRandomTopic && !nextProps.loadingRandomTopic && !this.props.randomTopic) {
      this.props.getRandomTopicVideos(nextProps.allTopics);
    }
  }

  render() {
    return (
      <section>
        <Player src={getVideo(this.props.id)} controls>
        </Player>
        <h2 className='video-player-title'>{this.props.title}</h2>
        <h3 className="video-player-date text-left">date {this.props.date} </h3>
        <p className="text-left">{this.props.description}</p>
        <RelatedVideos
          topicName={this.props.randomTopic || ''}
          allTopics={this.props.allTopics || []}
          topicCount={this.props.randomTopicCount}
          videos={this.props.randomTopicVideos || []}
          loading={this.props.loadingAllTopics || this.props.loadingRandomTopic}
          getRandomTopicVideos={this.props.getRandomTopicVideos}
        />
      </section>

    )
  }
}

//
// VideoPlayer.propTypes = {
//   title: PropTypes.string,
//   date: PropTypes.string,
//   description: PropTypes.string
// };


const mapStateToProps = state => ({
  allTopics: state.topics.allTopics,
  loadingAllTopics: state.topics.loadingAllTopics,
  randomTopic: state.topics.randomTopic,
  randomTopicCount: state.topics.randomTopicCount,
  loadingRandomTopic: state.topics.loadingRandomTopic,
  randomTopicVideos: state.topics.randomTopicVideos
});

const mapDispatchToProps = dispatch => ({
  getAllTopics: () => dispatch(getAllTopics()),
  getRandomTopicVideos: allTopics => dispatch(getRandomTopicVideos(allTopics))
});


export default connect(mapStateToProps, mapDispatchToProps)(VideoPlayer);