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

module.exports.SigninForm = React.createClass({
  getInitialState: function() {
    return {'hideMsg': true, 'msg': '', 'msgOk': false, 'password': '', 'email': ''};
  },
  handleSubmit: function(e) {
    Api.Call('SIGNIN', {'password': this.state.password, 'email': this.state.email}, 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();
  },
  handlePasswordChange: function(event) {
    this.setState({'password': event.target.value});
  },
  handleEmailChange: function(event) {
    this.setState({'email': 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});
    return (
        <div className='row justify-content-center sign-in'>
          <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'>
            <form role='form' onSubmit={this.handleSubmit}>
              <input className='form-control' type='email' placeholder='email' onChange={this.handleEmailChange} />
              <input className='form-control' type='password' placeholder='password' onChange={this.handlePasswordChange} />
              <input className='form-control submit' type='submit' value='Sign In' />
              <div className={cName} ref='message'>{this.state.msg}</div>
            </form>
            <a href='#' onClick={App.onInternNavigation.bind(this, '/signup')}><u>Sign up</u></a>
          </div>
        </div>
       );
  }
});

