"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

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

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

  _bluebird = function () {
    return data;
  };

  return data;
}

function _os() {
  const data = _interopRequireDefault(require("os"));

  _os = function () {
    return data;
  };

  return data;
}

function _tarStream() {
  const data = _interopRequireDefault(require("tar-stream"));

  _tarStream = function () {
    return data;
  };

  return data;
}

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _stream() {
  const data = _interopRequireDefault(require("stream"));

  _stream = function () {
    return data;
  };

  return data;
}

function _doctorRegistrarBuilder() {
  const data = _interopRequireDefault(require("../../../doctor/doctor-registrar-builder"));

  _doctorRegistrarBuilder = function () {
    return data;
  };

  return data;
}

function _doctorRegistrar() {
  const data = _interopRequireDefault(require("../../../doctor/doctor-registrar"));

  _doctorRegistrar = function () {
    return data;
  };

  return data;
}

function _diagnosis() {
  const data = _interopRequireDefault(require("../../../doctor/diagnosis"));

  _diagnosis = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../../../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../../../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../../../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function globalConfig() {
  const data = _interopRequireWildcard(require("./global-config"));

  globalConfig = function () {
    return data;
  };

  return data;
}

function _consumerLocator() {
  const data = require("../../../consumer/consumer-locator");

  _consumerLocator = function () {
    return data;
  };

  return data;
}

function _bitMap() {
  const data = _interopRequireDefault(require("../../../consumer/bit-map"));

  _bitMap = function () {
    return data;
  };

  return data;
}

function _missingDiagnosisName() {
  const data = _interopRequireDefault(require("./exceptions/missing-diagnosis-name"));

  _missingDiagnosisName = function () {
    return data;
  };

  return data;
}

function _diagnosisNotFound() {
  const data = _interopRequireDefault(require("./exceptions/diagnosis-not-found"));

  _diagnosisNotFound = function () {
    return data;
  };

  return data;
}

function _npmClient() {
  const data = _interopRequireDefault(require("../../../npm-client"));

  _npmClient = function () {
    return data;
  };

  return data;
}

let runningTimeStamp;

var _default =
/*#__PURE__*/
function () {
  var _runAll = (0, _bluebird().coroutine)(function* ({
    filePath
  }) {
    (0, _doctorRegistrarBuilder().default)();
    runningTimeStamp = _getTimeStamp();

    const doctorRegistrar = _doctorRegistrar().default.getInstance();

    const examineP = doctorRegistrar.diagnoses.map(diagnosis => diagnosis.examine());
    const examineResults = yield Promise.all(examineP);
    const envMeta = yield _getEnvMeta();
    const savedFilePath = yield _saveExamineResultsToFile(examineResults, envMeta, filePath);
    return {
      examineResults,
      savedFilePath,
      metaData: envMeta
    };
  });

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

  return runAll;
}();

exports.default = _default;

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

function _runOne() {
  _runOne = (0, _bluebird().coroutine)(function* ({
    diagnosisName,
    filePath
  }) {
    if (!diagnosisName) {
      throw new (_missingDiagnosisName().default)();
    }

    (0, _doctorRegistrarBuilder().default)();
    runningTimeStamp = _getTimeStamp();

    const doctorRegistrar = _doctorRegistrar().default.getInstance();

    const diagnosis = doctorRegistrar.getDiagnosisByName(diagnosisName);

    if (!diagnosis) {
      throw new (_diagnosisNotFound().default)(diagnosisName);
    }

    const examineResult = yield diagnosis.examine();
    const envMeta = yield _getEnvMeta();
    const savedFilePath = yield _saveExamineResultsToFile([examineResult], envMeta, filePath);
    return {
      examineResult,
      savedFilePath,
      metaData: envMeta
    };
  });
  return _runOne.apply(this, arguments);
}

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

function _listDiagnoses() {
  _listDiagnoses = (0, _bluebird().coroutine)(function* () {
    (0, _doctorRegistrarBuilder().default)();

    const doctorRegistrar = _doctorRegistrar().default.getInstance();

    return Promise.resolve(doctorRegistrar.diagnoses);
  });
  return _listDiagnoses.apply(this, arguments);
}

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

function _saveExamineResultsToFile2() {
  _saveExamineResultsToFile2 = (0, _bluebird().coroutine)(function* (examineResults, envMeta, filePath) {
    if (!filePath) {
      return Promise.resolve(undefined);
    }

    const finalFilePath = _calculateFinalFileName(filePath);

    const packStream = yield _generateExamineResultsTarFile(examineResults, envMeta);

    const yourTarball = _fsExtra().default.createWriteStream(finalFilePath);

    packStream.pipe(yourTarball);
    return new Promise(resolve => {
      yourTarball.on('close', function () {
        _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!')
        // })
      });
    });
  });
  return _saveExamineResultsToFile2.apply(this, arguments);
}

function _calculateFinalFileName(fileName) {
  if (fileName === '.') {
    return _getDefaultFileName();
  }

  let finalFileName = fileName;

  if ((0, _utils().getExt)(fileName) !== 'tar' && (0, _utils().getExt)(fileName) !== 'tar.gz') {
    finalFileName = `${(0, _utils().getWithoutExt)(finalFileName)}.tar`;
  }

  return finalFileName;
}

function _getDefaultFileName() {
  const timestamp = runningTimeStamp || _getTimeStamp();

  return `doctor-results-${timestamp}.tar`;
} // TODO: move to utils


function _getTimeStamp() {
  const d = new Date();
  const timestamp = d.getTime();
  return timestamp;
}

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

function _generateExamineResultsTarFile2() {
  _generateExamineResultsTarFile2 = (0, _bluebird().coroutine)(function* (examineResults, envMeta) {
    const pack = _tarStream().default.pack(); // pack is a streams2 stream


    const debugLog = yield _getDebugLogAsStream();
    const consumerInfo = yield _getConsumerInfo();
    let bitmap;

    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 pack;
  });
  return _generateExamineResultsTarFile2.apply(this, arguments);
}

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

function _getEnvMeta2() {
  _getEnvMeta2 = (0, _bluebird().coroutine)(function* () {
    const env = {
      nodeVersion: process.version,
      runningTimestamp: runningTimeStamp || _getTimeStamp(),
      platform: _os().default.platform(),
      bitVersion: _constants().BIT_VERSION,
      npmVersion: yield _npmClient().default.getNpmVersion(),
      yarnVersion: yield _npmClient().default.getYarnVersion(),
      userDetails: _getUserDetails()
    };
    return env;
  });
  return _getEnvMeta2.apply(this, arguments);
}

function _getUserDetails() {
  const name = globalConfig().getSync(_constants().CFG_USER_NAME_KEY) || '';
  const email = globalConfig().getSync(_constants().CFG_USER_EMAIL_KEY) || '';
  return `${name}<${email}>`;
}

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

function _getDebugLogAsStream2() {
  _getDebugLogAsStream2 = (0, _bluebird().coroutine)(function* () {
    const exists = _fsExtra().default.exists(_constants().DEBUG_LOG);

    if (exists) {
      return _fsExtra().default.readFile(_constants().DEBUG_LOG);
    }

    return Promise.resolve(undefined);
  });
  return _getDebugLogAsStream2.apply(this, arguments);
}

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

function _getConsumerInfo2() {
  _getConsumerInfo2 = (0, _bluebird().coroutine)(function* () {
    const consumerInfo = yield (0, _consumerLocator().getConsumerInfo)(process.cwd());
    return consumerInfo;
  });
  return _getConsumerInfo2.apply(this, arguments);
}

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