"use strict";

var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");
var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.default = prettierCode;
var _manifest = require("../lib/manifest.js");
var paths = _interopRequireWildcard(require("../lib/paths"));
var _index = require("../../cli-shared-utils/index.js");
function _getRequireWildcardCache(e) { if ("function" != typeof _WeakMap) return null; var r = new _WeakMap(), t = new _WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = _Object$defineProperty && _Object$getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? _Object$getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
const prettier = require('prettier');
const fs = require('fs');
const path = require('path');
const babel = require('@babel/core');

// 使用babel & prettier处理代码
function prettierCode(dir) {
  // 默认Unity的文件以及laya的main文件进行处理，微小转换的文件进行处理
  const manifest = (0, _manifest.get)();
  let option = {
    include: /(engine\/js\/main\.js)|(wxapi-adapter\.js)|(unity_plugin(?:_\d+\.\d+\.\d+)?\.js)|(webgl\.wasm\.framework\.unityweb\.js)/
  };
  if (manifest.engine && manifest.engine.includes('wx') || manifest.isUnity) {
    option = {
      include: /\.js$/,
      exclude: {
        test: filePath => {
          return filePath.includes('node_modules') || filePath.includes('@babel') || filePath.includes('laya') || filePath.includes('webgl.framework.js') || filePath.includes('unionSdk') || filePath.includes('unityAdapter.js') || filePath.includes('qgame-adapter.js') || filePath.includes('store.js');
        }
      }
    };
  }
  const files = [];
  traverseDirSync(dir, files, option);
  for (const file of files) {
    // 统一使用babel-loader处理
    babelCode(file, file);

    // 统一使用prettier格式化
    const content = fs.readFileSync(file, {
      encoding: 'utf-8'
    });
    if (content) {
      const formattedCode = prettier.format(content, {
        semi: true,
        singleQuote: true,
        parser: 'babel'
      });
      fs.writeFileSync(file, formattedCode, 'utf8');
    }
  }
}

/**
 * 遍历目录文件 同步方法
 * @param dir
 * @param files 收集的文件列表
 */
const traverseDirSync = function (dir, files, options) {
  const st = fs.statSync(dir);
  if (st && st.isFile()) {
    const isExclude = options && options.exclude && options.exclude.test(dir.replace(/\\/g, '/'));
    if (!isExclude && options && options.include) {
      if (options.include.test(dir.replace(/\\/g, '/'))) {
        files.push(dir);
      }
      return;
    }
    return;
  }
  const list = fs.readdirSync(dir);
  list.forEach(function (file) {
    const isExclude = options && options.exclude && options.exclude.test(file.replace(/\\/g, '/'));
    if (!isExclude) {
      file = path.join(dir, file);
      const stat = fs.statSync(file);
      if (stat && stat.isDirectory()) {
        traverseDirSync(file, files, options);
      } else {
        if (options && options.include) {
          if (options.include.test(file.replace(/\\/g, '/'))) {
            files.push(file);
          }
          return;
        }
        files.push(file);
      }
    }
  });
};
function babelCode(filePath) {
  const code = fs.readFileSync(filePath, 'utf8');
  try {
    // 检查代码中是否有严苛模式以及@babel/的标记，如果有则不进行babel转换
    if (code.includes('use strict') && code.includes('@babel/')) {
      (0, _index.info)(`[babel] babel not effective, ${filePath.replace(paths.PROJECT_PATH, '')}`);
      return;
    }

    // 将文件缓存到build_temp目录下
    if (filePath.startsWith(paths.PROJECT_PATH)) {
      const savePath = filePath.replace(paths.PROJECT_PATH, paths.BUILDTEMP);
      if (!fs.existsSync(path.dirname(savePath))) {
        fs.mkdirSync(path.dirname(savePath), {
          recursive: true
        });
      }
      fs.writeFileSync(savePath, code);
    }
    const result = babel.transformSync(code, {
      filename: path.basename(filePath),
      cwd: __dirname,
      // 设置工作目录
      presets: ['@babel/preset-env'],
      plugins: ['@babel/plugin-transform-modules-commonjs', '@babel/plugin-transform-optional-chaining', '@babel/plugin-transform-nullish-coalescing-operator'],
      compact: false
    });
    // babel将src下内容转换下，到dist下

    if (!fs.existsSync(path.dirname(filePath))) {
      fs.mkdirSync(path.dirname(filePath), {
        recursive: true
      });
    }
    fs.writeFileSync(filePath, result.code);
    (0, _index.info)(`[babel] success ${filePath.replace(paths.PROJECT_PATH, '')}`);
  } catch (e) {
    (0, _index.info)(`[babel] error ${filePath.replace(paths.PROJECT_PATH, '')}`);
  }
}