const { removeDir, copyDir, fix2 } = require('./utils');
const compressing = require('compressing');
let fs = require('fs');

async function main() {
  await removeDir('../dist/web_desktop');
  const projectName = await getBundleName('../play/build_web_desktop/web-desktop/assets');
  await copyDir(`../play/build_web_desktop/web-desktop/assets/${projectName}`, '../dist/web_desktop');
  await removeDir('../play/build_web_desktop');

  const bundleData = {
    ios: await getBundleData('../dist/ios'),
    android: await getBundleData('../dist/android'),
  }

  fs.writeFileSync('../dist/config.json', JSON.stringify(bundleData));

  const tarStream = new compressing.zip.Stream();
  tarStream.addEntry('../dist/play');
  tarStream.addEntry('../dist/ios');
  tarStream.addEntry('../dist/android');
  tarStream.addEntry('../dist/web_desktop');
  tarStream.addEntry('../dist/config.json');

  const destStream = fs.createWriteStream(`../publish/${getReleaseFileName()}.zip`);
  tarStream.pipe(destStream);

  console.log('打包完成！');

  // 删掉发布打包的多余文件
  await removeDir('../play/library');
  await removeDir('../play/local');
  await removeDir('../play/temp');
}

async function getBundleName(path) {
  const paths = fs.readdirSync(path);
  return paths.find(path => path != 'internal' && path !='main');
}

async function getBundleData(path) {
  const bundleData = {
    sceneName: '',
    version: '',
  }
  const paths = fs.readdirSync(path);
  bundleData.sceneName = paths[0];
  const files = fs.readdirSync(path + '/' + bundleData.sceneName);
  files.forEach(fileName => {
    fileName.split('.').forEach((str, idx, arr) => {
      if (str == 'config') {
        bundleData.version = arr[idx + 1];
      }
    })
  });
  return bundleData;
}

function getReleaseFileName() {
  let date = new Date();
  let fileName = `Release_${date.getFullYear()}${fix2(date.getMonth() + 1)}${fix2(date.getDate())} `;
  fileName += `${fix2(date.getHours())}-${fix2(date.getMinutes())}-${fix2(date.getSeconds())}`;
  return fileName;
}

main();