import { getMatchListFromReg } from '../regexp/regexp.mjs';
import { readFileSync, writeFileSync } from '../fs/fs.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/fs.mjs';
import '../nodejs/os.mjs';

/**
 * 为 Vue 组件添加 emits 属性
 * @param {string} filePath 组件地址
 * @param {string} [fileContent] 组件内容
 * @returns {string} 新的组件内容
 *
 * @example
 * ```ts
 * addNameForComponent('xxx.vue');
 * ```
 */
function addEmitsForComponent(filePath) {
  var fileContent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var content = fileContent;
  if (!content) {
    content = readFileSync(filePath, false);
  }
  if (/emits:\s*\[/.test(content)) return;
  var emits = getEmitList(content);
  if (!emits.length) return;
  var newSource = content.replace(/(?=\s\sdata\(\)\s*\{)/, getEmitsStr(emits));
  writeFileSync(filePath, newSource);
  return newSource;
}
function getEmitList(source) {
  var reg = /emit\('([^',]+)'/g;
  var emits = getMatchListFromReg(source, reg);
  var array = Array.from(new Set(emits));
  array.sort();
  return array;
}
function getEmitsStr(emits) {
  var emitsStr = emits.map(function (item) {
    return "'".concat(item, "'");
  }).join(',\n    ');
  return ['  emits: [', "    ".concat(emitsStr, ","), '  ],\n'].join('\n');
}

export { addEmitsForComponent };
