import React from 'react';
import ReactNative from 'react-native';
import PropTypes from 'prop-types';

const {
  Component,
} = React;

const {
  StyleSheet,
  requireNativeComponent,
  NativeModules,
  View,
} = ReactNative;

export default class RCTVnPlayer extends Component {

  constructor(props, context) {
    super(props, context);
      this.fullscreen = this.fullscreen.bind(this);
      this.play = this.play.bind(this)
      this._assignRoot = this._assignRoot.bind(this);
      this._onStateChanged = this._onStateChanged.bind(this);
      this._onNewStream = this._onNewStream.bind(this);
      this._onNewFrame = this._onNewFrame.bind(this);
  }

  setNativeProps(nativeProps) {
    this._root.setNativeProps(nativeProps);
  }

  fullscreen(isFull) {
    this.setNativeProps({fullscreen:isFull});
  }

  play(isPlay) {
    this.setNativeProps({play:isPlay});
  }

  _assignRoot(component) {
    this._root = component;
  }

  _onStateChanged(event) {
    if (this.props.onStateChanged) {
      this.props.onStateChanged(event.nativeEvent);
    }
  }

  _onNewStream(event) {
    if (this.props.onNewStream) {
      this.props.onNewStream(event.nativeEvent);
    }
  }

  _onNewFrame(event) {
    if (this.props.onNewFrame) {
      this.props.onNewFrame(event.nativeEvent);
    }
  }

  render() {
    const {
      source
    } = this.props;
    source.initOptions = source.initOptions || [];
    const nativeProps = Object.assign({}, this.props);
    Object.assign(nativeProps, {
        style: [styles.base, nativeProps.style],
        source: source,
        play: false,
        onStateChanged: this._onStateChanged,
        onNewStream: this._onNewStream,
        onNewFrame: this._onNewFrame,
    });

    return (
      <VnPlayer ref={this._assignRoot} {...nativeProps} />
    );
  }

}

RCTVnPlayer.propTypes = {
    fullscreen: PropTypes.bool,
    play: PropTypes.bool,
    source: PropTypes.object,
    onStateChanged: PropTypes.func,
    onNewStream: PropTypes.func,
    onNewFrame: PropTypes.func,

  ...View.propTypes,
};

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  }
});
const VnPlayer = requireNativeComponent('VnPlayer', RCTVnPlayer);
