"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _serializeError() {
  const data = _interopRequireDefault(require("serialize-error"));

  _serializeError = function () {
    return data;
  };

  return data;
}

function _scope() {
  const data = require("../../api/scope");

  _scope = function () {
    return data;
  };

  return data;
}

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

function _runAndUpdateCI() {
  _runAndUpdateCI = (0, _bluebird().coroutine)(function* ({
    id,
    scopePath,
    verbose,
    directory,
    keep,
    noCache
  }) {
    function addCIAttrsInTheModel({
      error,
      startTime
    }) {
      const endTime = Date.now().toString();
      const ciProps = {
        startTime,
        endTime,
        error: undefined
      };

      if (error) {
        const serializedError = (0, _serializeError().default)(error);
        ciProps.error = serializedError;
        return (0, _scope().modifyCIProps)(scopePath, id, ciProps);
      }

      return (0, _scope().modifyCIProps)(scopePath, id, ciProps);
    }

    const startTime = Date.now().toString();

    try {
      // define options
      const save = true;
      const buildResults = yield (0, _scope().buildInScope)({
        id,
        scopePath,
        save,
        verbose,
        directory,
        keep,
        noCache
      });
      const testResults = yield (0, _scope().testInScope)({
        id,
        scopePath,
        save,
        verbose,
        directory,
        keep
      });
      const dists = buildResults ? buildResults.dists : null;
      yield addCIAttrsInTheModel({
        startTime
      });
      return {
        specsResults: testResults,
        dists
      };
    } catch (e) {
      yield addCIAttrsInTheModel({
        error: e,
        startTime
      });
      throw e;
    }
  });
  return _runAndUpdateCI.apply(this, arguments);
}

module.exports = runAndUpdateCI;