'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _process = require('process');

var _process2 = _interopRequireDefault(_process);

var _inquirer = require('inquirer');

var _inquirer2 = _interopRequireDefault(_inquirer);

var _validator = require('validator');

var _validator2 = _interopRequireDefault(_validator);

var _debug = require('../utils/debug');

var _debug2 = _interopRequireDefault(_debug);

var _analytics = require('../utils/analytics');

var _printTools = require('../utils/print-tools');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const { debug } = (0, _debug2.default)('cmd-login');

class Login {
  constructor(context) {
    debug('Login.constructor');
    this.context = context;
    this.session = context.session;
  }

  static displayWelcomeMessage(user) {
    (0, _printTools.echo)();
    (0, _printTools.echo)(4)(`Welcome back ${_chalk2.default.cyan(user.email)}. You're already logged in!`);
    (0, _printTools.echo)();
  }

  static displayLoginMessage() {
    (0, _printTools.echo)();
    (0, _printTools.echo)(4)(`Welcome to ${_chalk2.default.cyan('Syncano')} (${_chalk2.default.dim('syncano.io')})`);
    (0, _printTools.echo)(4)('Please login or create an account by entering your email and password:');
    (0, _printTools.echo)();
  }

  static displayNewAccountMessage() {
    (0, _printTools.echo)();
    (0, _printTools.echo)(4)(`${_chalk2.default.green('New account has been created!')}`);
    (0, _printTools.echo)();
  }

  run([cmd]) {
    return this.session.checkAuth().then(user => Login.displayWelcomeMessage(user)).catch(err => this.promptLogin());
  }

  loginCallback(resp, loginType) {
    this.session.settings.account.set('auth_key', resp.account_key);
    this.session.load().then(() => {
      if (loginType === 'signup') {
        (0, _analytics.track)('CLI: Sign up');
      } else {
        (0, _analytics.track)('CLI: Sign in');
      }
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)(`${_chalk2.default.green('You\'re in! Enjoy!')} 👍`);
      (0, _printTools.echo)();
    });
  }

  register({ email, password }) {
    return this.session.getAnonymousConnection().Account.register({ email, password }).then(resp => {
      Login.displayNewAccountMessage();
      return this.loginCallback(resp, 'signup');
    }).catch(registerErr => {
      (0, _printTools.echo)(`Register error: ${registerErr.message}`);
      _process2.default.exit();
    });
  }

  loginOrRegister({ email, password }) {
    var _this = this;

    debug('Registering/Logging in', email);
    return this.session.connection.Account.login({ email, password }).then(resp => this.loginCallback(resp)).catch((() => {
      var _ref = _asyncToGenerator(function* (loginErr) {
        if (loginErr.message === 'Invalid email.') {
          debug('Login failed, trying to register');
          yield Login.promptCreation();
          return _this.register({ email, password });
        }
        (0, _printTools.echo)(4)('Authentication error! 😢');
        (0, _printTools.echo)();
        (0, _printTools.echo)(4)(loginErr.message);
      });

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    })());
  }

  static promptCreation() {
    return _asyncToGenerator(function* () {
      debug('Login.promptCreation()');

      const confirmQuestion = [{
        type: 'confirm',
        name: 'confirm',
        message: (0, _printTools.p)(8)('This email doesn\'t exists. Do you want to create new account?'),
        default: false
      }];

      const { confirm } = (yield _inquirer2.default.prompt(confirmQuestion)) || {};
      if (confirm === false) return _process2.default.exit();
    })();
  }

  promptLogin() {
    debug('Login.promptLogin()');

    const loginQuestion = {
      name: 'email',
      message: (0, _printTools.p)(8)('Your e-mail'),
      validate: value => _validator2.default.isEmail(value) || 'E-mail is required!'
    };

    const passwordQuestion = {
      name: 'password',
      message: (0, _printTools.p)(8)('Password'),
      type: 'password',
      validate: value => _validator2.default.isLength(value, { min: 5 }) || 'Password must contain at least 5 characters.'
    };

    Login.displayLoginMessage();

    return _inquirer2.default.prompt([loginQuestion, passwordQuestion]).then(resp => this.loginOrRegister(resp));
  }
}
exports.default = Login;
module.exports = exports['default'];
//# sourceMappingURL=login.js.map