import * as fs from 'fs';
import * as path from 'path';
import * as fsExtra from 'fs-extra';
import { getPackageInfo } from '../utils/package';

const packagesPath = path.resolve(__dirname, '../../');
const selfPackagePath = path.resolve(__dirname, '../');
function getPackages(): string[] {
  const selfName = selfPackagePath.split(/(\\|\/)/).pop()!;
  return fs
    .readdirSync(packagesPath, { withFileTypes: true, encoding: 'utf-8' })
    .filter(dir => {
      if (!dir.isDirectory()) {
        return false;
      }
      if (dir.name === selfName || dir.name === 'components') {
        return false;
      }
      if (fs.existsSync(path.resolve(packagesPath, './', dir.name, './package.json'))) {
        return true;
      }
      return false;
    })
    .map(dir => dir.name);
}

/**
 * 收集该package的文档内容
 * @param packageDirName 包的目录名称
 */
function pickDocs(packageDirName: string): void {
  const basePath = path.resolve(packagesPath, './', packageDirName);
  const docsPath = path.resolve(basePath, './docs');
  const packageName = getPackageInfo(path.resolve(basePath, './package.json')).name.split('/').pop()!;
  const packageIndexFileName = packageName + '.md';

  if (fs.existsSync(docsPath)) {
    console.log(`正在收集 ${packageName} 的文档`);

    const targetPath = path.resolve(selfPackagePath, './document/', packageName);

    fs.mkdirSync(targetPath, { recursive: true });

    fs.readdirSync(docsPath, { withFileTypes: true }).forEach(file => {
      if (file.name === 'wk-docs-out') {
        // wk-docs-cli 生成的内容 直接移动到document目录下
        fsExtra.copySync(path.resolve(docsPath, './wk-docs-out/'), path.resolve(selfPackagePath, './document/'));
      } else if (file.name === packageIndexFileName) {
        // 索引文件 移动到document目录下
        fsExtra.copySync(path.resolve(docsPath, './', file.name), path.resolve(selfPackagePath, './document/'));
      } else {
        // 自己手动写的内容 全部移动到document/<packageName>下
        if (file.isDirectory()) {
          fsExtra.copySync(path.resolve(docsPath, './', file.name), path.resolve(targetPath, './', file.name));
        } else {
          fsExtra.copySync(path.resolve(docsPath, './', file.name), targetPath);
        }
      }
    });
  } else {
    console.log(`skip ${packageName} : 文档目录不存在`);
  }
}

function run() {
  console.log('正在获取package列表');
  const packages = getPackages();
  bakDocument();
  for (const dirName of packages) {
    pickDocs(dirName);
  }
}

function bakDocument() {
  const documentPath = path.resolve(selfPackagePath, './document');
  if (fs.existsSync(documentPath)) {
    console.log('正在备份原文件');
    const bakPath = path.resolve(selfPackagePath, './document_bak');
    fsExtra.emptyDirSync(bakPath);
    fsExtra.copySync(documentPath, path.resolve(selfPackagePath, './document_bak'));
  }
  fsExtra.emptyDirSync(documentPath);
}

run();
