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

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

    if (!financialAid || (financialAid.lastAction && financialAid.lastAction.status === 'error') || !financialAid.data) {
      const requestParams = {
        url: __FINANCIAL_AID_URL__,
        auth: [__USERNAME__, __PASSWORD__],
      };

      this.props.fetch(requestParams);
    }
  }

  invalidateFinancialAid() {
    const requestParams = {
      url: __FINANCIAL_AID_URL__,
      auth: [__USERNAME__, __PASSWORD__],
    };

    this.props.invalidate(requestParams);
  }

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

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

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

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

    return (
      <div>
        <h2>Financial Aid Service</h2>
        <input className='invalidateBtn' type='button' value='Invalidate Financial Aid' onClick={() => this.invalidateFinancialAid()} />
        <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;
FinancialAid.propTypes = {
  financialAid: object,
  fetch: func,
  invalidate: func,
};
