import React, { Component, PropTypes } from 'react';
import ObjectInspector from 'react-object-inspector';

export default class Schedule extends Component {
  componentDidMount() {
    const { schedule } = this.props;

    if (!schedule || (schedule.lastAction && schedule.lastAction.status === 'error') || !schedule.data) {
      const requestParams = {
        url: __SCHEDULE_URL__,
        auth: [__USERNAME__, __PASSWORD__],
      };
      const term = '';
      const mode = '2';
      const acadCareer = '';

      this.props.fetch(requestParams, term, mode, acadCareer);
    }
  }

  invalidateSchedule() {
    const requestParams = {
      url: __SCHEDULE_URL__,
      auth: [__USERNAME__, __PASSWORD__],
    };
    const term = '';
    const mode = '2';
    const acadCareer = '';

    this.props.invalidate(requestParams, term, mode , acadCareer);
  }

  copyToClipboard() {
    const copyText = JSON.stringify(this.props.schedule.data);
    window.prompt('Copy Response:', copyText);
  }

  render() {
    let isFetching = false;
    let hasData = false;
    let responseDisp = '';

    if (this.props.schedule) {
      isFetching = this.props.schedule.isFetching;

      if (this.props.schedule.data) {
        hasData = true;
        const json = this.props.schedule.data;
        responseDisp = <ObjectInspector data={json}/>;
      }
    }

    return (
      <div>
        <h2>Schedule Service</h2>
        <input className="invalidateBtn" type="button" value="Invalidate Schedule" onClick={() => this.invalidateSchedule()} />
        <input className="copyBtn" type="button" value="Copy Response" onClick={() => this.copyToClipboard()} disabled={isFetching || !hasData} />
        <br/><br/>
        {isFetching ? <p>Fetching Data...</p> : responseDisp}
        <br/>
      </div>
    );
  }
}

const { func, object } = PropTypes;
Schedule.propTypes = {
  schedule: object,
  fetch: func,
  invalidate: func,
};
