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

const { func, object } = PropTypes;

export default class ServiceCall extends Component {
  componentWillMount() {
    const serviceParams = {
      // The parameters used for the call
      requestParams: {
        url: '',
        auth: [__USERNAME__, __PASSWORD__],
      },
    };

    this.props.fetch(serviceParams);
  }

  invalidateServiceCall() {
    const fetchParams = {
      /**
       * The parameters that will be used to refresh the data. This usually is the same as the
       * parameters that were used to originally fetch the data.
       */
      requestParams: {
        url: '',
        auth: [__USERNAME__, __PASSWORD__],
      },
    };

    this.props.invalidate(fetchParams);
  }

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

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

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

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

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

ServiceCall.propTypes = {
  serviceState: object,
  fetch: func.isRequired,
  invalidate: func.isRequired,
};
