"use strict";

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

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

require("core-js/modules/es.array.iterator");

require("core-js/modules/es.promise");

require("core-js/modules/es.string.replace");

var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");

var _mapInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/map");

_Object$defineProperty(exports, "__esModule", {
  value: true
});

exports.default = void 0;

var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));

var _lastIndexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/last-index-of"));

var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator"));

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireWildcard(require("path"));

var _util = require("util");

var _plugin = _interopRequireDefault(require("@start/plugin"));

var _lodash = require("lodash");

const readdir = (0, _util.promisify)(_fs.default.readdir);
const mkdir = (0, _util.promisify)(_fs.default.mkdir);
const exists = (0, _util.promisify)(_fs.default.exists);
const writeFile = (0, _util.promisify)(_fs.default.writeFile);
const readFile = (0, _util.promisify)(_fs.default.readFile);
const appendFile = (0, _util.promisify)(_fs.default.appendFile);
const lstat = (0, _util.promisify)(_fs.default.lstat);

var _default = () => (0, _plugin.default)('CREATE DOCS', ({
  reporter
}) =>
/*#__PURE__*/
(0, _asyncToGenerator2.default)(function* () {
  const repoPath = (0, _path.resolve)(process.cwd(), '../..');
  const distDir = (0, _path.resolve)(process.cwd(), '_dist');

  if (!(yield exists(distDir))) {
    reporter.emit('error', '_dist directory not found');
    return;
  }

  const loadReadme =
  /*#__PURE__*/
  function () {
    var _ref2 = (0, _asyncToGenerator2.default)(function* (file, location) {
      const filePath = _path.default.join(repoPath, location, file); // ex. packages/pfm-profile


      const readme = _path.default.join(filePath, 'README.md');

      if (yield exists(readme)) {
        const packageJsonFile = _path.default.join(filePath, '/package.json');

        let version = '';

        if (exists(packageJsonFile)) {
          const packageJsonObj = JSON.parse(_fs.default.readFileSync(packageJsonFile, 'utf8'));
          version = packageJsonObj.version;
        }

        const content = yield readFile(readme, 'utf8');

        if (content) {
          return content.replace('# ' + file, '## ' + file + ' ' + version);
        }
      }
    });

    return function loadReadme(_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }();

  try {
    // Read the lerna packages location
    const lernaFile = (0, _path.resolve)(repoPath, 'lerna.json');

    if (!(yield exists(lernaFile))) {
      reporter.emit('error', 'No lerna file found', repoPath);
      return;
    }

    const lernaJsonObj = JSON.parse(_fs.default.readFileSync(lernaFile, 'utf8'));

    if (!(0, _lodash.has)(lernaJsonObj, 'packages')) {
      reporter.emit('error', 'No paths for packages found in lerna.json file');
      return;
    }

    const docsDir = (0, _path.resolve)(distDir, 'docs');
    yield mkdir(docsDir); // For each package location
    //		create a file in docs called that location with .md at the end (so apps.md, packages.md)

    yield _promise.default.all((0, _mapInstanceProperty(_lodash))(lernaJsonObj.packages,
    /*#__PURE__*/
    function () {
      var _ref3 = (0, _asyncToGenerator2.default)(function* (location) {
        const packageDirName = location.substr(0, (0, _lastIndexOf.default)(location).call(location, _path.default.sep)); // packages/* -> packages

        const fileName = packageDirName + '.md';
        const title = '# ' + packageDirName.charAt(0).toUpperCase() + (0, _slice.default)(packageDirName).call(packageDirName, 1) + '\n\n\n';

        const readmeFilePath = _path.default.join(docsDir, fileName);

        yield writeFile(readmeFilePath, title, 'utf8'); // For each package in the location
        // 		append it's README.md file to the doc file with its package name a level 2 title and the version as well

        const packageDirectory = _path.default.join(repoPath, location.substr(0, (0, _lastIndexOf.default)(location).call(location, _path.default.sep) + 1));

        const packageNames = yield readdir(packageDirectory);
        (0, _mapInstanceProperty(_lodash))(packageNames,
        /*#__PURE__*/
        function () {
          var _ref4 = (0, _asyncToGenerator2.default)(function* (packgageName) {
            const isDirectory = (yield lstat(_path.default.join(packageDirectory, packgageName))).isDirectory();

            if (isDirectory) {
              const readme = yield loadReadme(packgageName, packageDirName);

              if (readme) {
                appendFile(readmeFilePath, readme + '\n\n\n');
              }
            }
          });

          return function (_x4) {
            return _ref4.apply(this, arguments);
          };
        }());
      });

      return function (_x3) {
        return _ref3.apply(this, arguments);
      };
    }())); // Create a repo.md file in docs that combines the root README with the other docs and stamps with the current repo version

    const repoMdFile = _path.default.join(docsDir, 'repo.md');

    const rootDirName = repoPath.split(_path.default.sep).pop();
    const title = '# ' + rootDirName + ' v.' + lernaJsonObj.version + '\n\n\n';
    yield writeFile(repoMdFile, title, 'utf8');
    const readme = yield readFile(_path.default.join(repoPath, 'README.md'), 'utf8');

    if (readme) {
      appendFile(repoMdFile, readme);
    }
  } catch (e) {
    reporter.emit('error', 'Create docs', e);
  }
}));

exports.default = _default;
module.exports = exports.default;