"use strict";

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

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

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

var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");

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

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

exports.default = void 0;

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

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

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");

function _getRequireWildcardCache(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = _Object$defineProperty && _Object$getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { _Object$defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 copyFile = (0, _util.promisify)(_fs.default.copyFile);
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 currentApp = _path.default.basename(_path.default.resolve(process.cwd()));

  const repoPath = (0, _path.resolve)(process.cwd(), '../..');
  const distDir = (0, _path.resolve)(process.cwd(), '_dist');
  const cliMdFile = (0, _path.resolve)(__dirname, '../../../README.md');

  if (!(yield exists(distDir))) {
    yield mkdir('_dist');
  }

  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 content = yield readFile(readme, 'utf8');

        if (content) {
          return content;
        }
      }
    });

    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 docsDir = (0, _path.resolve)(distDir, 'docs');

    if (!(yield exists(docsDir))) {
      yield mkdir(docsDir);
    }

    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;
    } // Read the releasePattern file


    const releasePatternFile = (0, _path.resolve)(process.cwd(), 'releasePattern.json');
    let releasePatternJsonObj = null;

    if (yield exists(releasePatternFile)) {
      releasePatternJsonObj = JSON.parse(_fs.default.readFileSync(releasePatternFile, 'utf8'));
    }

    if (releasePatternJsonObj && releasePatternJsonObj.releasePattern) {
      // Check if a releaseNotes file exists in the apps folder already and copy to the docs folder
      const releaseFileName = releasePatternJsonObj.releasePattern.replace('$', lernaJsonObj.version + '.md');
      const releaseNotesFile = (0, _path.join)((0, _path.resolve)(process.cwd(), 'releaseNotes'), releaseFileName);

      if (yield exists(releaseNotesFile)) {
        //copy to docs
        const destinationReleaseNotesFile = (0, _path.join)(docsDir, 'releaseNotes.md');
        yield copyFile(releaseNotesFile, destinationReleaseNotesFile);
      }
    } // 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.replace('/*', ''); // packages/* -> packages

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

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

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

        const packageDirectory = _path.default.join(repoPath, packageDirName);

        const packageNames = yield readdir(packageDirectory);
        (0, _mapInstanceProperty(_lodash))(packageNames, /*#__PURE__*/function () {
          var _ref4 = (0, _asyncToGenerator2.default)(function* (packageName) {
            //Only append app readme from the current app
            if (packageDirName === 'apps' && packageName !== currentApp) {
              return;
            }

            const isDirectory = (yield lstat(_path.default.join(packageDirectory, packageName))).isDirectory();

            if (isDirectory) {
              const readme = yield loadReadme(packageName, 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);
    } // Add @meniga/cli readme file to docs


    if (yield exists(cliMdFile)) {
      const cliReadme = yield readFile(cliMdFile, 'utf8');

      if (cliReadme) {
        const repoCliMdFile = _path.default.join(docsDir, 'tools.md');

        yield writeFile(repoCliMdFile, cliReadme, 'utf8');
      }
    }
  } catch (e) {
    reporter.emit('error', 'Create docs', e);
  }
}));

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