var Api        = require('./api.js').Api;
var App        = require('./app.js');
var classNames = require('classnames');

var OtpQrCode = React.createClass({
  render: function() {
    return (
      <div>
        <img src={this.props.img} />
        <p>{this.props.secret}</p>
      </div>
    );
  }
});

module.exports.OtpEnrollForm = React.createClass({
  getInitialState: function() {
    return {'hideMsg': true, 'msg': '', 'msgOk': false, 'pass': ''};
  },
  handleSubmit: function(e) {
    Api.Call('OTP_VALIDATE', {'pass': this.state.pass}, function(err, status, data) {
      if (err) {
        console.error(err, data);
        this.displayMessage(App.errorCodeToMessage(err.code), false);
        return;
      }

      this.displayMessage('OK', true);
      this.props.onSuccess(data.token);

    }.bind(this));

    e.preventDefault();
  },
  handlePassChange: function(event) {
    this.setState({'pass': event.target.value});
  },
  hideMessage: function() {
    this.setState({'hideMsg': true});
  },
  displayMessage: function(msg, ok) {
    this.setState({'msg': msg, 'msgOk': ok, 'hideMsg': false});
  },
  render: function() {
    var cName  = classNames('form-message', {'hidden': this.state.hideMsg, 'message-ok': this.state.msgOk});
    var qrCode = null;

    if (this.props.img) {
      qrCode = (
        <div className='row justify-content-center'>
          <OtpQrCode img={this.props.img} secret={this.props.secret} />
        </div>
      );
    }
    return (
        <div className='row otp-enroll justify-content-center'>
          <div className='col-lg-offset-4 col-lg-4 col-md-offset-4 col-md-4 col-sm-offset-4 col-sm-4 col-xs-offset-1 col-xs-10'>
            {qrCode}
            <div className='row justify-content-center'>
              <form role='form' onSubmit={this.handleSubmit}>
                <input className='form-control' type='pass' placeholder='pass' onChange={this.handlePassChange} />
                <input className='form-control submit' type='submit' value='Validate' />
                <div className={cName} ref='message'>{this.state.msg}</div>
              </form>
            </div>
          </div>
        </div>
       );
  }
});
