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

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

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

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

  invalidateCourseHistory() {
    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.courses.data);
    window.prompt('Copy Response:', copyText);
  }

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

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

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

    return (
      <div>
        <h2>Course History Service</h2>
        <input className="invalidateBtn" type="button" value="Invalidate Course History" onClick={() => this.invalidateCourseHistory()} />
        <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;
CourseHistory.propTypes = {
  courses: object,
  fetch: func,
  invalidate: func,
};
