import Api from './api.js';
import React from 'react';

class PoloniexConfiguration extends React.Component {
  constructor(props) {
    super(props);
    this.state = {'apiKey': '', 'apiSecret': '', 'apiRequested': false, 'status': 'loading'};
  }

  checkCredentials = () => {
    Api.Call('MARKET_TEST_CREDENTIALS', {'name': 'poloniex'}, function(err, status, data) {
      if (err) {
        console.error(err, data);
        if (err.code === 'invalid_market_credentials') {
          this.setState({'status': 'invalidCredentials'});
        } else if (err.code === 'ip_restricted_api_key') {
          this.setState({'status': 'ipRestricted'});
        }
        return;
      }

      this.setState({'status': 'ok'});
    }.bind(this));
  }

  handleCredentialsChange = (key, secret) => {
    this.setState({'apiKey': key, 'apiSecret': secret});
  }

  handleCredentialsSubmit = () => {
    this.setState({'status': 'loading'});
    Api.Call('UPDATE_MARKET', {'key': this.state.apiKey, 'secret': this.state.apiSecret, 'name': 'poloniex'}, function(err, status, data) {
      if (err) {
        console.error(err, data);
        if (err.code === 'invalid_market_credentials') {
          this.setState({'status': 'invalidCredentials'});
        } else if (err.code === 'ip_restricted_api_key') {
          this.setState({'status': 'ipRestricted'});
        }
        return;
      }

      this.setState({'status': 'loading'});
      this.checkCredentials();
    }.bind(this));
  }

  componentDidMount = () => {
    Api.Call('MARKET', {'name': 'poloniex'}, function(err, status, data) {
      this.setState({'apiRequested': true});
      if (err) {
        console.error(err, data);
        return;
      }

      var newStatus = this.state.status;
      if (!data.key || !data.secret) {
        newStatus = 'emptyCredentials';
      } else {
        this.checkCredentials();
      }

      this.setState({'apiKey': data.key, 'apiSecret': data.secret, 'status': newStatus});
    }.bind(this));
  }

  render = () => {
    var displayText = null;
    switch (this.state.status) {
      case 'loading':
        displayText = 'Checking Poloniex credentials...';
        break;
      case 'invalidCredentials':
        displayText = 'Invalid poloniex credentials';
        break;
      case 'ipRestricted':
        displayText = 'Your API key is IP restricted.';
        break;
      case 'emptyCredentials':
        displayText = 'Please provide poloniex credentials';
        break;
      case 'ok':
        displayText = 'You are all set !';
        break;
      default:
        console.error('unknown status', this.state.status);
        displayText = null;
    }
    if (this.state.apiRequested === false) {
      return <div></div>;
    }
    return (
      <div>
        <PoloniexCredentialsForm onLoadCredentials={this.onLoadCredentials}
                                 onCredentialsSubmit={this.handleCredentialsSubmit}
                                 onCredentialsChange={this.handleCredentialsChange}
                                 apiSecret={this.state.apiSecret}
                                 apiKey={this.state.apiKey}
                                 status={this.state.status}
                                 statusMessage={displayText}/>
      </div>
    );
  }
}

class PoloniexCredentialsForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {'editMode': false};
  }

  handleSubmit = (e) => {
    this.props.onCredentialsSubmit();
    this.setState({'editMode': false});
    e.preventDefault();
  }

  handleApiKeyChange = (event) => {
    this.props.onCredentialsChange(event.target.value, this.props.apiSecret);
  }

  handleApiSecretChange = (event) => {
    this.props.onCredentialsChange(this.props.apiKey, event.target.value);
  }

  onEditClick = () => {
    this.setState({'editMode': true});
  }

  render = () => {
    var submitType      = this.state.editMode === true ? 'submit' : 'hidden';
    var buttonDisplay   = this.state.editMode === true ? 'none' : 'inline';
    var secretDisplayed = this.state.editMode === true ? this.props.apiSecret : 'XXXXXXX';
    var keyDisplayed    = this.state.editMode === true ? this.props.apiKey : 'XXXXXXX';

    var iconName = 'icon-cancel-circled';
    switch (this.props.status) {
      case 'loading':
        iconName = 'icon-hourglass-2';
        break;
      case 'ok':
        iconName = 'icon-ok-circled';
        break;
    }

    return (
        <div className="row api-credentials-form">
          <div className="offset-2 col-8 box">
            <span className="text-center">Poloniex credentials</span>
            <hr/>
            <div className="row config-status">
              <div className="col-12">
                <span><i className={iconName}></i>{this.props.statusMessage}</span>
              </div>
            </div>
            <div className="row">
              <div className="col-12">
                <form role="form" onSubmit={this.handleSubmit}>
                  <label className="w-100">Key:
                    <input className="form-control" type="text" placeholder="key" value={keyDisplayed} onChange={this.handleApiKeyChange} disabled={!this.state.editMode}/>
                  </label>
                  <label className="w-100">Secret:
                    <input className="form-control" type="text" placeholder="secret" value={secretDisplayed} onChange={this.handleApiSecretChange} disabled={!this.state.editMode}/>
                  </label>
                  <input className="form-control submit" type={submitType} value="Save" />
                  <button className="form-control submit" style={{display: buttonDisplay}} onSubmit={null} onClick={this.onEditClick} type="button">Show/Edit</button>
                </form>
              </div>
            </div>
          </div>
        </div>
       );
  }
}

export default PoloniexConfiguration;
