'use strict';

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

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _inquirer = require('inquirer');

var _inquirer2 = _interopRequireDefault(_inquirer);

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

class SocketEndpointCall {
  constructor(context) {
    this.context = context;
    this.session = context.session;
    this.Socket = context.Socket;
  }

  static validateValue(value) {
    if (!value) {
      return 'We need this!';
    }

    return true;
  }

  static promptParamQuestion(params, param) {
    const description = params[param].description || '';
    const paramType = params[param].type;
    (0, _printTools.echo)(4)(`- ${param} ${_chalk2.default.dim(`(${paramType})`)} ${description}`);
    const question = {
      name: param,
      message: (0, _printTools.p)(2)(`Type in value for "${_chalk2.default.green(param)}" parameter`),
      default: params[param].example,
      validate: value => SocketEndpointCall.validateValue(value)
    };
    return question;
  }

  static listParams(endpointObj) {
    const params = endpointObj.metadata.parameters || {};
    const paramsCount = Object.keys(params).length;
    const questions = [];

    if (!paramsCount) return questions;

    (0, _printTools.echo)();
    (0, _printTools.echon)(4)(`You can pass ${_chalk2.default.cyan(paramsCount)} `);
    (0, _printTools.echo)(`parameter(s) to ${_chalk2.default.cyan(endpointObj.getFullName())} endpoint:`);
    (0, _printTools.echo)();

    Object.keys(params).forEach(param => {
      questions.push(this.promptParamQuestion(params, param));
    });
    (0, _printTools.echo)();

    return questions;
  }

  static formatResponse(res, bodyOnly) {
    // Callback for the HTTP request response
    const contentType = res.headers['content-type'];

    (0, _printTools.echo)();
    if (!bodyOnly) {
      (0, _printTools.echo)(4)(_chalk2.default.grey('statusCode:'), (0, _printTools.printCode)(res.status));
      (0, _printTools.echo)(4)(_chalk2.default.grey('content-type:'), res.headers['content-type']);
      (0, _printTools.echo)(4)(_chalk2.default.grey('body:'));
    }

    (0, _printTools.echo)();
    (0, _printTools.echo)((0, _printTools.p)(bodyOnly ? 0 : 4)((0, _printTools.printSourceCode)(contentType, res.data)));
    (0, _printTools.echo)();
  }

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

    return _asyncToGenerator(function* () {
      try {
        const bodyOnly = cmd.body;
        const socketName = fullEndpointName.split('/')[0];
        const endpointName = fullEndpointName.split('/')[1];
        const socket = yield _this.Socket.get(socketName);
        const endpointObj = yield socket.getEndpoint(endpointName);

        if (endpointObj && endpointObj.existRemotely) {
          const askQuestions = SocketEndpointCall.listParams(endpointObj);
          const resp = (yield _inquirer2.default.prompt(askQuestions)) || {};

          endpointObj.call(resp).then(function (res) {
            return SocketEndpointCall.formatResponse(res, bodyOnly);
          }).catch(function (err) {
            if (err.response) {
              SocketEndpointCall.formatResponse(err.response);
            } else {
              (0, _printTools.error)(err);
            }
          });
        } else {
          (0, _printTools.error)('No such endpoint on the server! Make sure you have synced your socket.');
        }
      } catch (err) {
        (0, _printTools.error)(err);
      }
    })();
  }
}

exports.default = SocketEndpointCall;
module.exports = exports['default'];
//# sourceMappingURL=socket-call.js.map