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

/* React component which can trigger a call periodically and pass the callback result to its child */
class PeriodicRefresher extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.initialValue,
      isWaitingForPeriodicCallBack: false,
    };

    this.intervalId = null;
    this.setRepetition = this.setRepetition.bind(this);
    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);

    if (this.props.isEnabled) {
      this.setRepetition();
    }
  }

  render() {
    return React.cloneElement(this.props.children, {
      periodicdata: this.state.data,
    });
  }

  componentDidUpdate() {
    if (this.props.isEnabled) {
      this.setRepetition();
    } else if (this.props.isEnabled !== undefined) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }

  componentWillUnmount() {
    clearInterval(this.intervalId);
  }

  onSuccess(data) {
    this.setState({ data, isWaitingForPeriodicCallBack: false });
    this.props.onCallbackSuccess(data);
  }

  onFailure() {
    this.setState({ isWaitingForPeriodicCallBack: false });
    console.log('Periodic callback failed');
  }

  setRepetition() {
    if (this.intervalId === null) {
      this.intervalId = setInterval(() => {
        if (!this.state.isWaitingForPeriodicCallBack) {
          this.setState({ isWaitingForPeriodicCallBack: true });
          return this.props.periodicCallback(this.onSuccess, this.onFailure);
        }
      }, this.props.intervalInMilliSeconds);
    }
  }
}

PeriodicRefresher.propTypes = {
  /* Initial value returned in periodicData property to PeriodicRefresher's child. Can be anything. It must be a similar object to what periodic data will return in normal operation */
  initialValue: PropTypes.any,
  /* Timer interval between 2 calls to the callback periodicCallback */
  intervalInMilliSeconds: PropTypes.number.isRequired,
  /* whether the period call is enabled or disabled */
  isEnabled: PropTypes.bool,
  /* callback function which will be triggered periodically */
  periodicCallback: PropTypes.func.isRequired,
};
export default PeriodicRefresher;
