'use strict';

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

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _inquirer = require('inquirer');

var _inquirer2 = _interopRequireDefault(_inquirer);

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

var _hostingSync = require('./hosting-sync');

var _hostingSync2 = _interopRequireDefault(_hostingSync);

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

var _hosting2 = _interopRequireDefault(_hosting);

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"); }); }; }

class HostingAdd {
  constructor(context) {
    this.context = context;
    this.session = context.session;
    this.Socket = context.Socket;
    this.hostingName = null;
    this.socket = null;
  }

  run([folder, cmd]) {
    var _this = this;

    return _asyncToGenerator(function* () {
      _this.folder = folder;
      _this.socketName = cmd.socket;
      _this.cname = cmd.cname;
      _this.fullPath = null;

      if (!_fs2.default.existsSync(_this.folder)) {
        (0, _printTools.echo)();
        (0, _printTools.error)(4)('Provided path doesn\'t exist.');
        (0, _printTools.echo)(4)(`Type ${_chalk2.default.green('mkdir <folder_name>')} to create a folder.`);
        (0, _printTools.echo)();
        process.exit(1);
      }

      const responses = (yield _inquirer2.default.prompt(_this.getQuestions())) || {};

      _this.hostingName = responses.name;

      if (_this.socketName) {
        // TODO: implement Socket level hosting
        const params = {};
        _this.socket = yield _this.Socket.get(cmd.socket || responses.socket);
        _this.socket.addHosting(_this.hostingName, params);
      } else {
        const params = {
          name: _this.hostingName,
          src: _path2.default.relative(_this.session.projectPath, _path2.default.join(process.cwd(), _this.folder)),
          cname: _this.cname || responses.CNAME || null
        };
        _hosting2.default.add(params).then(function (resp) {
          return _this.syncNewHosting();
        }).catch(function (err) {
          (0, _printTools.echo)();
          try {
            (0, _printTools.error)(4)(err.response.data.detail);
          } catch (printErr) {
            (0, _printTools.error)(4)(printErr.message);
          }
          (0, _printTools.echo)();
        });
      }
    })();
  }

  syncNewHosting() {
    var _this2 = this;

    return _asyncToGenerator(function* () {
      const syncQuestion = [{
        type: 'confirm',
        name: 'confirm',
        message: (0, _printTools.p)(2)('Do you want to sync files now?'),
        default: false
      }];

      const response = yield _inquirer2.default.prompt(syncQuestion);
      (0, _printTools.echo)();

      if (!response.confirm) {
        (0, _printTools.echo)(4)(`To sync files use: ${_chalk2.default.cyan(`syncano-cli hosting sync ${_this2.hostingName}`)}`);
        (0, _printTools.echo)();
        return process.exit();
      }

      new _hostingSync2.default(_this2.context).run([_this2.hostingName, { socket: _this2.socket ? _this2.socket.name : null }]);
    })();
  }

  getQuestions() {
    const questions = [{
      name: 'name',
      message: (0, _printTools.p)(2)("Set hosting's name"),
      default: 'staging',
      validate: value => {
        if (!value) {
          return 'This parameter is required!';
        }
        return true;
      }
    }];

    if (!this.cname) {
      questions.push({
        name: 'CNAME',
        message: (0, _printTools.p)(2)('Set CNAME now (your own domain) or leave it empty')
      });
    }

    return questions;
  }
}

exports.default = HostingAdd;
module.exports = exports['default'];
//# sourceMappingURL=hosting-add.js.map