'use strict';

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var _serializeError;

function _load_serializeError() {
  return _serializeError = _interopRequireDefault(require('serialize-error'));
}

var _test;

function _load_test() {
  return _test = require('../api/consumer/lib/test');
}

var _externalError;

function _load_externalError() {
  return _externalError = _interopRequireDefault(require('../error/external-error'));
}

var _loader;

function _load_loader() {
  return _loader = _interopRequireDefault(require('../cli/loader'));
}

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"); }); }; }
// TODO - move to language specific driver.


var testOneComponent = function testOneComponent(verbose) {
  return function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(id) {
      var res;
      return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, (_test || _load_test()).testInProcess)(id, verbose);

            case 2:
              res = _context.sent;
              return _context.abrupt('return', res[0]);

            case 4:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, undefined);
    }));

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

function run() {
  // Start the loader to make sure we show it on forked process
  (_loader || _load_loader()).default.on();
  var ids = process.env.__ids__ ? process.env.__ids__.split() : undefined;
  var verbose = process.env.__verbose__ === true;
  if (!ids || !ids.length) {
    return (0, (_test || _load_test()).testInProcess)(undefined, verbose).then(function (results) {
      var serializedResults = serializeResults(results);
      // $FlowFixMe
      return process.send(serializedResults);
    }).catch(function (e) {
      (_loader || _load_loader()).default.off();
      var serializedResults = serializeResults(e);
      // $FlowFixMe
      return process.send(serializedResults);
    });
  }
  var testAllP = ids.map(testOneComponent(verbose));
  return Promise.all(testAllP).then(function (results) {
    var serializedResults = serializeResults(results);
    // $FlowFixMe
    return process.send(serializedResults);
  }).catch(function (e) {
    (_loader || _load_loader()).default.off();
    var serializedResults = serializeResults(e);
    // $FlowFixMe
    return process.send(serializedResults);
  });
}

run();

function serializeResults(results) {
  if (!results) return undefined;
  if (results instanceof Error) {
    // In case of extenral error also serialize the original error
    if (results instanceof (_externalError || _load_externalError()).default) {
      results.originalError = (0, (_serializeError || _load_serializeError()).default)(results.originalError);
    }

    var serializedErr = (0, (_serializeError || _load_serializeError()).default)(results);
    var finalResults = {
      type: 'error',
      error: serializedErr
    };
    return finalResults;
  }
  var serializeFailure = function serializeFailure(failure) {
    if (!failure) return undefined;
    var serializedFailure = failure;
    if (failure.err && failure.err instanceof Error) {
      serializedFailure.err = (0, (_serializeError || _load_serializeError()).default)(failure.err);
    }
    return serializedFailure;
  };

  var serializeSpec = function serializeSpec(spec) {
    if (!spec.failures) return spec;
    spec.failures = spec.failures.map(serializeFailure);
    return spec;
  };

  var serializeResult = function serializeResult(result) {
    if (!result.specs) return result;
    result.specs = result.specs.map(serializeSpec);
    return result;
  };

  var serializedResults = results.map(serializeResult);
  return { type: 'results', results: serializedResults };
}