'use strict';

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

var _syncano = require('syncano');

var _syncano2 = _interopRequireDefault(_syncano);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _nodeWalkup = require('node-walkup');

var _nodeWalkup2 = _interopRequireDefault(_nodeWalkup);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

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

var _debug2 = _interopRequireDefault(_debug);

var _settings = require('../settings');

var _settings2 = _interopRequireDefault(_settings);

var _uniqueInstance = require('./unique-instance');

var _uniqueInstance2 = _interopRequireDefault(_uniqueInstance);

var _sockets = require('./sockets');

var _sockets2 = _interopRequireDefault(_sockets);

var _init = require('./init');

var _init2 = _interopRequireDefault(_init);

var _hosting = require('./hosting');

var _hosting2 = _interopRequireDefault(_hosting);

var _plugins = require('./plugins');

var _plugins2 = _interopRequireDefault(_plugins);

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

var _printTools = require('./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 _bluebird2.default(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 _bluebird2.default.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const { debug } = (0, _debug2.default)('utils-session');

class Session {
  constructor() {
    this.settings = null;
    this.projectPath = null;
    this.project = null;
    this.userId = null;
    this.walkup = _bluebird2.default.promisify(_nodeWalkup2.default);

    this.HOST = process.env.SYNCANO_HOST || 'api.syncano.io';
    this.ENDPOINT_HOST = this.HOST === 'api.syncano.io' ? 'syncano.space' : 'syncano.link';
  }

  getSpaceHost() {
    if (this.project && this.project.instance) {
      return `${this.project.instance}.${this.ENDPOINT_HOST}`;
    }
  }

  getInitInstance() {
    return new _init2.default(this);
  }

  getPluginsInstance() {
    return new _plugins2.default(this);
  }

  getBaseURL() {
    return `https://${this.getHost()}`;
  }

  getHost() {
    return this.HOST;
  }

  getDistPath() {
    const distPath = _path2.default.join(this.projectPath, '.dist');
    _mkdirp2.default.sync(distPath);
    return distPath;
  }

  getBuildPath() {
    const buildPath = _path2.default.join(this.projectPath, '.build');
    _mkdirp2.default.sync(buildPath);
    return buildPath;
  }

  getAnonymousConnection() {
    this.connection = new _syncano2.default({
      baseUrl: this.getBaseURL()
    });
    return this.connection;
  }

  createConnection() {
    debug('createConnection');
    if (this.settings.account.authenticated()) {
      this.connection = new _syncano2.default({
        accountKey: this.settings.account.getAuthKey(),
        baseUrl: this.getBaseURL()
      });

      if (this.project && this.project.instance) {
        this.connection.defaults = { instanceName: this.project.instance };
      }
    } else {
      this.connection = (0, _syncano2.default)({ baseUrl: this.getBaseURL() });
    }

    return this.connection.Account.getUserDetails().then(details => {
      this.userId = details.id;
      (0, _analytics.identify)(details);
    }).catch(() => {});
  }

  createInstance(name = (0, _uniqueInstance2.default)()) {
    debug('Creating Instance');
    (0, _printTools.echo)();
    (0, _printTools.echon)(4)('Creating Syncano Instance... ');
    return this.connection.Instance.please().create({ name }).then(newInstance => {
      (0, _printTools.echo)(`${_chalk2.default.green('Done')}`);
      (0, _printTools.echo)(4)(`Syncano Instance ${_chalk2.default.cyan(newInstance.name)} has been created!`);
      (0, _printTools.echo)();
      return newInstance;
    }).catch(err => {
      (0, _printTools.error)(err.message || 'Connection error');
      process.exit();
    });
  }

  getInstance(instanceName) {
    return this.connection.Instance.please().get({ name: instanceName || this.project && this.project.instance }).then(instance => instance).catch(() => false);
  }

  getInstances() {
    var _this = this;

    return _asyncToGenerator(function* () {
      const instances = yield _this.connection.Instance.please().list();

      return instances;
    })();
  }

  checkAuth() {
    var _this2 = this;

    return _asyncToGenerator(function* () {
      const userDetails = yield _this2.connection.Account.getUserDetails();
      return new _bluebird2.default(function (resolve, reject) {
        if (userDetails) {
          return resolve(userDetails);
        }
        reject();
      });
    })();
  }

  static findProjectPath() {
    return new _bluebird2.default((resolve, reject) => {
      if (_fsExtra2.default.existsSync('syncano.yml')) {
        return resolve(process.cwd());
      }
      if (_fsExtra2.default.existsSync('syncano/syncano.yml')) {
        return resolve(_path2.default.join(process.cwd(), 'syncano'));
      }

      const searchInPath = pathToCheck => {
        if (pathToCheck === process.env.HOME) {
          return resolve(null);
        }

        const files = _fsExtra2.default.readdirSync(pathToCheck);

        if (_lodash2.default.includes(files, 'syncano.yml')) {
          resolve(pathToCheck);
        }

        const nextFolder = _path2.default.parse(pathToCheck);
        if (nextFolder.name) {
          searchInPath(nextFolder.dir);
        }
      };

      searchInPath(process.cwd());
    });
  }

  load() {
    debug('load');

    // Checking all folders up
    return Session.findProjectPath().then(projectPath => {
      debug('Searching for syncano.yml', projectPath);

      if (projectPath) {
        this.settings = (0, _settings2.default)(projectPath);
        this.project = this.settings.account.getProject(projectPath);
        this.projectPath = projectPath;
      } else {
        this.projectPath = process.cwd();
        this.settings = (0, _settings2.default)(this.projectPath);
      }

      if (!projectPath) {
        this.project = this.settings.account.getProject(this.projectPath);
      }

      return this.createConnection();
    }).then(() => this).catch(err => {
      this.settings = (0, _settings2.default)();
      return this;
    });
  }

  loadPlugins(program, context) {
    new _plugins2.default(this).load(program, context);
  }

  isAuthenticated() {
    if (!this.settings.account.authenticated()) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)('You are not looged in!');
      (0, _printTools.echo)(4)(`Type ${_chalk2.default.cyan('syncano-cli login')} for login to your account.`);
      (0, _printTools.echo)();
      process.exit();
    }
  }

  isAuthenticatedToInit() {
    if (!this.settings.account.authenticated()) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)(_chalk2.default.red('You have to be a logged in to be able an initialize a new project!'));
      (0, _printTools.echo)();
    }
  }

  checkConnection(instanceName) {
    var _this3 = this;

    return _asyncToGenerator(function* () {
      const instance = yield _this3.getInstance(instanceName);

      if (!instance) {
        (0, _printTools.echo)();
        (0, _printTools.echo)(4)(`Instance ${_chalk2.default.cyan(instanceName || _this3.project.instance)} was not found on your account!`);
        (0, _printTools.echo)();

        if (instanceName) return process.exit();

        (0, _printTools.echo)(4)(`Type ${_chalk2.default.cyan('syncano-cli attach')} to choose one of the existing instances.`);
        (0, _printTools.echo)();

        return process.exit();
      }

      return instance;
    })();
  }

  hasProject() {
    if (!this.projectPath) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)(`I don't see any project here. Try ${_chalk2.default.cyan('syncano-cli init')}.`);
      (0, _printTools.echo)();
      process.exit();
    }
    if (!this.project) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)('You have to attach this project to one of your instances.');
      (0, _printTools.echo)(4)(`Try ${_chalk2.default.cyan('syncano-cli attach')}.`);
      (0, _printTools.echo)();
      process.exit();
    }
  }

  hasSocket(socketName) {
    // eslint-disable-line class-methods-use-this
    const socket = new _sockets2.default(socketName);
    if (!socket.existLocally) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)('File socket.yml was not found in a project directory!');
      (0, _printTools.echo)(4)(`Check your directory or try ${_chalk2.default.cyan('syncano-cli socket create')} to create a new Socket.`);
      (0, _printTools.echo)();
      process.exit();
    }
  }

  notAlreadyInitialized() {
    if (this.projectPath && this.project) {
      (0, _printTools.echo)();
      (0, _printTools.echo)(4)('You are fine! Project in this folder is already initiated!');
      (0, _printTools.echo)(4)(`It is using ${_chalk2.default.cyan(this.project.instance)} Syncano instance.`);
      (0, _printTools.echo)();
      process.exit();
    }
  }

  deployProject() {
    // eslint-disable-line class-methods-use-this
    return _hosting2.default.list().then(hostings => _bluebird2.default.all(hostings.map(hosting => hosting.deploy())));
  }
}

exports.Session = Session;
exports.default = new Session();
//# sourceMappingURL=session.js.map