import React, { PropTypes } from 'react';
const { func, object } = PropTypes;
import ObjectInspector from 'react-object-inspector';

export default React.createClass({
  propTypes: {
    profile: object,
    fetch: func,
    invalidate: func,
  },

  componentDidMount() {
    const { profile } = this.props;
    if (!profile || (profile.lastAction && profile.lastAction.status === 'error') || !profile.data) {
      const requestParams = {
        url: __PROFILE_URL__,
        auth: [__USERNAME__, __PASSWORD__],
      };

      this.props.fetch(requestParams);
    }
  },

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

    this.props.invalidate(requestParams);
  },

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

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

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

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

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