'use strict';

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

var _regenerator;

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

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

var runOne = exports.runOne = function () {
  var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(_ref4) {
    var diagnosisName = _ref4.diagnosisName,
        filePath = _ref4.filePath;
    var doctorRegistrar, diagnosis, examineResult, envMeta, savedFilePath;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (diagnosisName) {
              _context2.next = 2;
              break;
            }

            throw new (_missingDiagnosisName || _load_missingDiagnosisName()).default();

          case 2:
            (0, (_doctorRegistrarBuilder || _load_doctorRegistrarBuilder()).default)();
            runningTimeStamp = _getTimeStamp();
            doctorRegistrar = (_doctorRegistrar || _load_doctorRegistrar()).default.getInstance();
            diagnosis = doctorRegistrar.getDiagnosisByName(diagnosisName);

            if (diagnosis) {
              _context2.next = 8;
              break;
            }

            throw new (_diagnosisNotFound || _load_diagnosisNotFound()).default(diagnosisName);

          case 8:
            _context2.next = 10;
            return diagnosis.examine();

          case 10:
            examineResult = _context2.sent;
            _context2.next = 13;
            return _getEnvMeta();

          case 13:
            envMeta = _context2.sent;
            _context2.next = 16;
            return _saveExamineResultsToFile([examineResult], envMeta, filePath);

          case 16:
            savedFilePath = _context2.sent;
            return _context2.abrupt('return', { examineResult, savedFilePath, metaData: envMeta });

          case 18:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));

  return function runOne(_x2) {
    return _ref3.apply(this, arguments);
  };
}();

var listDiagnoses = exports.listDiagnoses = function () {
  var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3() {
    var doctorRegistrar;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            (0, (_doctorRegistrarBuilder || _load_doctorRegistrarBuilder()).default)();
            doctorRegistrar = (_doctorRegistrar || _load_doctorRegistrar()).default.getInstance();
            return _context3.abrupt('return', Promise.resolve(doctorRegistrar.diagnoses));

          case 3:
          case 'end':
            return _context3.stop();
        }
      }
    }, _callee3, this);
  }));

  return function listDiagnoses() {
    return _ref5.apply(this, arguments);
  };
}();

var _saveExamineResultsToFile = function () {
  var _ref6 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(examineResults, envMeta, filePath) {
    var finalFilePath, packStream, yourTarball;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            if (filePath) {
              _context4.next = 2;
              break;
            }

            return _context4.abrupt('return', Promise.resolve(undefined));

          case 2:
            finalFilePath = _calculateFinalFileName(filePath);
            _context4.next = 5;
            return _generateExamineResultsTarFile(examineResults, envMeta);

          case 5:
            packStream = _context4.sent;
            yourTarball = (_fsExtra || _load_fsExtra()).default.createWriteStream(finalFilePath);


            packStream.pipe(yourTarball);

            return _context4.abrupt('return', new Promise(function (resolve) {
              yourTarball.on('close', function () {
                (_logger || _load_logger()).default.info(`wrote a file by bit doctor, file path: ${finalFilePath}`);
                resolve(finalFilePath);
                // fs.stat(finalFilePath, function (err, stats) {
                //   if (err) throw err
                //   console.log(stats)
                //   console.log('Got file info successfully!')
                // })
              });
            }));

          case 9:
          case 'end':
            return _context4.stop();
        }
      }
    }, _callee4, this);
  }));

  return function _saveExamineResultsToFile(_x3, _x4, _x5) {
    return _ref6.apply(this, arguments);
  };
}();

var _generateExamineResultsTarFile = function () {
  var _ref7 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(examineResults, envMeta) {
    var pack, debugLog, consumerInfo, bitmap;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            pack = (_tarStream || _load_tarStream()).default.pack(); // pack is a streams2 stream

            _context5.next = 3;
            return _getDebugLogAsStream();

          case 3:
            debugLog = _context5.sent;
            _context5.next = 6;
            return _getConsumerInfo();

          case 6:
            consumerInfo = _context5.sent;
            bitmap = void 0;

            if (consumerInfo && consumerInfo.path) {
              bitmap = _getBitMap(consumerInfo.path);
            }
            pack.entry({ name: 'env-meta.json' }, JSON.stringify(envMeta, null, 2));
            pack.entry({ name: 'doc-results.json' }, JSON.stringify(examineResults, null, 2));
            if (debugLog) {
              pack.entry({ name: 'debug.log' }, debugLog);
            }
            if (bitmap) {
              pack.entry({ name: '.bitmap' }, bitmap);
            }
            if (consumerInfo && consumerInfo.consumerConfig) {
              pack.entry({ name: 'config.json' }, JSON.stringify(consumerInfo.consumerConfig.toPlainObject(), null, 4));
            }

            pack.finalize();

            return _context5.abrupt('return', pack);

          case 16:
          case 'end':
            return _context5.stop();
        }
      }
    }, _callee5, this);
  }));

  return function _generateExamineResultsTarFile(_x6, _x7) {
    return _ref7.apply(this, arguments);
  };
}();

var _getEnvMeta = function () {
  var _ref8 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6() {
    var env;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.t0 = process.version;
            _context6.t1 = runningTimeStamp || _getTimeStamp();
            _context6.t2 = (_os || _load_os()).default.platform();
            _context6.t3 = (_constants || _load_constants()).BIT_VERSION;
            _context6.next = 6;
            return (_npmClient || _load_npmClient()).default.getNpmVersion();

          case 6:
            _context6.t4 = _context6.sent;
            _context6.next = 9;
            return (_npmClient || _load_npmClient()).default.getYarnVersion();

          case 9:
            _context6.t5 = _context6.sent;
            _context6.t6 = _getUserDetails();
            env = {
              nodeVersion: _context6.t0,
              runningTimestamp: _context6.t1,
              platform: _context6.t2,
              bitVersion: _context6.t3,
              npmVersion: _context6.t4,
              yarnVersion: _context6.t5,
              userDetails: _context6.t6
            };
            return _context6.abrupt('return', env);

          case 13:
          case 'end':
            return _context6.stop();
        }
      }
    }, _callee6, this);
  }));

  return function _getEnvMeta() {
    return _ref8.apply(this, arguments);
  };
}();

var _getDebugLogAsStream = function () {
  var _ref9 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7() {
    var exists;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            exists = (_fsExtra || _load_fsExtra()).default.exists((_constants || _load_constants()).DEBUG_LOG);

            if (!exists) {
              _context7.next = 3;
              break;
            }

            return _context7.abrupt('return', (_fsExtra || _load_fsExtra()).default.readFile((_constants || _load_constants()).DEBUG_LOG));

          case 3:
            return _context7.abrupt('return', Promise.resolve(undefined));

          case 4:
          case 'end':
            return _context7.stop();
        }
      }
    }, _callee7, this);
  }));

  return function _getDebugLogAsStream() {
    return _ref9.apply(this, arguments);
  };
}();

var _getConsumerInfo = function () {
  var _ref10 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8() {
    var consumerInfo;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.next = 2;
            return (0, (_consumerLocator || _load_consumerLocator()).getConsumerInfo)(process.cwd());

          case 2:
            consumerInfo = _context8.sent;
            return _context8.abrupt('return', consumerInfo);

          case 4:
          case 'end':
            return _context8.stop();
        }
      }
    }, _callee8, this);
  }));

  return function _getConsumerInfo() {
    return _ref10.apply(this, arguments);
  };
}();

var _os;

function _load_os() {
  return _os = _interopRequireDefault(require('os'));
}

var _tarStream;

function _load_tarStream() {
  return _tarStream = _interopRequireDefault(require('tar-stream'));
}

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _stream;

function _load_stream() {
  return _stream = _interopRequireDefault(require('stream'));
}

var _doctorRegistrarBuilder;

function _load_doctorRegistrarBuilder() {
  return _doctorRegistrarBuilder = _interopRequireDefault(require('../../../doctor/doctor-registrar-builder'));
}

var _doctorRegistrar;

function _load_doctorRegistrar() {
  return _doctorRegistrar = _interopRequireDefault(require('../../../doctor/doctor-registrar'));
}

var _diagnosis;

function _load_diagnosis() {
  return _diagnosis = _interopRequireDefault(require('../../../doctor/diagnosis'));
}

var _utils;

function _load_utils() {
  return _utils = require('../../../utils');
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../../../logger/logger'));
}

var _constants;

function _load_constants() {
  return _constants = require('../../../constants');
}

var _globalConfig;

function _load_globalConfig() {
  return _globalConfig = _interopRequireWildcard(require('./global-config'));
}

var _consumerLocator;

function _load_consumerLocator() {
  return _consumerLocator = require('../../../consumer/consumer-locator');
}

var _bitMap;

function _load_bitMap() {
  return _bitMap = _interopRequireDefault(require('../../../consumer/bit-map'));
}

var _missingDiagnosisName;

function _load_missingDiagnosisName() {
  return _missingDiagnosisName = _interopRequireDefault(require('./exceptions/missing-diagnosis-name'));
}

var _diagnosisNotFound;

function _load_diagnosisNotFound() {
  return _diagnosisNotFound = _interopRequireDefault(require('./exceptions/diagnosis-not-found'));
}

var _npmClient;

function _load_npmClient() {
  return _npmClient = _interopRequireDefault(require('../../../npm-client'));
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// run specific check
var runningTimeStamp = void 0;

exports.default = function () {
  var _ref = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(_ref2) {
    var filePath = _ref2.filePath;
    var doctorRegistrar, examineP, examineResults, envMeta, savedFilePath;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            (0, (_doctorRegistrarBuilder || _load_doctorRegistrarBuilder()).default)();
            runningTimeStamp = _getTimeStamp();
            doctorRegistrar = (_doctorRegistrar || _load_doctorRegistrar()).default.getInstance();
            examineP = doctorRegistrar.diagnoses.map(function (diagnosis) {
              return diagnosis.examine();
            });
            _context.next = 6;
            return Promise.all(examineP);

          case 6:
            examineResults = _context.sent;
            _context.next = 9;
            return _getEnvMeta();

          case 9:
            envMeta = _context.sent;
            _context.next = 12;
            return _saveExamineResultsToFile(examineResults, envMeta, filePath);

          case 12:
            savedFilePath = _context.sent;
            return _context.abrupt('return', { examineResults, savedFilePath, metaData: envMeta });

          case 14:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

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

  return runAll;
}();

function _calculateFinalFileName(fileName) {
  if (fileName === '.') {
    return _getDefaultFileName();
  }
  var finalFileName = fileName;
  if ((0, (_utils || _load_utils()).getExt)(fileName) !== 'tar' && (0, (_utils || _load_utils()).getExt)(fileName) !== 'tar.gz') {
    finalFileName = `${(0, (_utils || _load_utils()).getWithoutExt)(finalFileName)}.tar`;
  }
  return finalFileName;
}

function _getDefaultFileName() {
  var timestamp = runningTimeStamp || _getTimeStamp();
  return `doctor-results-${timestamp}.tar`;
}

// TODO: move to utils
function _getTimeStamp() {
  var d = new Date();
  var timestamp = d.getTime();
  return timestamp;
}

function _getUserDetails() {
  var name = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_USER_NAME_KEY) || '';
  var email = (_globalConfig || _load_globalConfig()).getSync((_constants || _load_constants()).CFG_USER_EMAIL_KEY) || '';
  return `${name}<${email}>`;
}

function _getBitMap(workspaceDir) {
  return (_bitMap || _load_bitMap()).default.loadRawSync(workspaceDir);
}