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

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

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

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

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

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

  tarStream.pipe(destStream);

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

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();