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

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

  handleSubmit = (e) => {
    Api.Call(
    'CHANGE_PASSWORD',
    {
      'password': this.state.password,
      'token': this.props.token
    },
    function(err, status, data) {
      if (err) {
        console.error(err, data);
        this.displayMessage(App.errorCodeToMessage(err.code), false);
        return;
      }

      this.displayMessage('You password has been reset.', true);
      this.props.onSuccess();

    }.bind(this)
);
    e.preventDefault();
  }

  handlePasswordChange = (event) => {
    this.setState({'password': 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});
    return (
        <div className="row sign-in">
          <div className="offset-4 col-4 col-xs-offset-1 col-xs-10 text-center">
            <form role="form" onSubmit={this.handleSubmit}>
              <input className="form-control" type="password" placeholder="password" onChange={this.handlePasswordChange} />
              <input className="form-control submit" type="submit" value="Change password" />
              <div className={cName}>{this.state.msg}</div>
            </form>
          </div>
        </div>
       );
  }
}

export default ChangePasswordForm;
