import { readFileSync } from '../fs/fs.mjs';
import { traverseFolder } from '../fs/fs-util.mjs';
import { getFs } from '../nodejs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/os.mjs';
import '@babel/runtime/helpers/toConsumableArray';
import '../time/time.mjs';

/**
 * 统计页面总数、分包数目等
 * @param dist
 * @returns result
 *
 * @example
 * ```ts
 * getPageTotal('./dist/dev/mp-weixin')
 * ```
 */
function getPageTotal(dist) {
  var _a;
  var appJson = getPath().resolve(dist, 'app.json');
  var result = {
    pageTotal: 0,
    subPackageTotal: 0
  };
  if (!getFs().existsSync(appJson)) {
    return result;
  }
  var data = readFileSync(appJson, true);
  var _data$pages = data.pages,
    pages = _data$pages === void 0 ? [] : _data$pages;
  var subPackages = ((_a = data.subPackages) === null || _a === void 0 ? void 0 : _a.length) ? data.subPackages : data.subpackages || [];
  result.pageTotal = pages.length + subPackages.reduce(function (acc, item) {
    var _a;
    acc += ((_a = item.pages) === null || _a === void 0 ? void 0 : _a.length) || 0;
    return acc;
  }, 0);
  result.subPackageTotal = subPackages.length;
  return result;
}
/**
 * 统计组件数目、wxml大小、wxss大小、js大小等
 * @param dist
 * @returns result
 *
 * @example
 * ```ts
 * getComponentInfo('./dist/dev/mp-weixin')
 * ```
 */
function getComponentInfo(dist) {
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    wxmlPostfix: '.wxml',
    wxssPostfix: '.wxss',
    vendorNames: ['common/vendor-1.js', 'common/vendor.js']
  };
  var result = {
    componentTotal: 0,
    wxsstTotal: 0,
    jsTotal: 0,
    wxmlSizeTotal: 0,
    wxssSizeTotal: 0,
    jsSizeTotal: 0,
    vendorJsSize: 0
  };
  if (!getFs().existsSync(dist)) {
    return result;
  }
  var isVendorJs = function isVendorJs(file) {
    var _a;
    return !!((_a = config.vendorNames) === null || _a === void 0 ? void 0 : _a.find(function (item) {
      return file.endsWith(item);
    }));
  };
  try {
    traverseFolder(function (tPath) {
      var fileSize = getFs().statSync(tPath).size;
      if (tPath.endsWith(config.wxmlPostfix)) {
        result.componentTotal += 1;
        result.wxmlSizeTotal += fileSize;
      }
      if (tPath.endsWith(config.wxssPostfix)) {
        result.wxsstTotal += 1;
        result.wxssSizeTotal += fileSize;
      }
      if (tPath.endsWith('.js')) {
        result.jsTotal += 1;
        result.jsSizeTotal += fileSize;
      }
      if (isVendorJs(tPath)) {
        result.vendorJsSize += fileSize;
      }
    }, dist);
  } catch (err) {
    console.log('traverseFolder.error: ', err);
  }
  return result;
}

export { getComponentInfo, getPageTotal };
