import Api from './api.js';
import App from './app.js';
import classNames from 'classnames';
import React from 'react';

class OtpQrCode extends React.Component {
  render = () => {
    return (
      <div>
        <img src={this.props.img} />
        <p>{this.props.secret}</p>
      </div>
    );
  }
}

class OtpEnrollForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {'hideMsg': true, 'msg': '', 'msgOk': false, 'pass': ''};
  }

  handleSubmit = (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 = (event) => {
    this.setState({'pass': event.target.value});
  }

  hideMessage = () => {
    this.setState({'hideMsg': true});
  }

  displayMessage = (msg, ok) => {
    this.setState({'msg': msg, 'msgOk': ok, 'hideMsg': false});
  }

  render = () => {
    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">
          <p>Please setup 2FA (Google Authenticator, Authy)</p>
          <OtpQrCode img={this.props.img} secret={this.props.secret} />
        </div>;
}
    return (
        <div className="row otp-enroll">
          <div className="offset-1 col-10 box offset-md-4 col-md-4 text-center">
            {qrCode}
            <div className="row justify-content-center">
              <form role="form" onSubmit={this.handleSubmit}>
                <label className="w-100 text-left"><strong>Code</strong></label>
                <input className="form-control" type="pass" onChange={this.handlePassChange} />
                <input className="form-control submit" type="submit" value="Validate" />
                <div className={cName}>{this.state.msg}</div>
              </form>
            </div>
          </div>
        </div>
       );
  }
}

export default OtpEnrollForm;
