const {chalkTag, fsExtra, findApp, copyFiles, fs, path} = require("../../bin/tools");

/**
 * 初始化打包配置文件
 */
const init = () => {
  chalkTag.info('开始运行项目打包工具...')
  return new Promise(resolve => fs.readdir('./src/project', (err, files) => {
    resolve(files.filter(e => e.indexOf('.') < 0))
  }))
}
/**
 * 拷贝对应文件
 */
const generateMain = project => {
  const getApps = new Promise(resolve => {
    const appLib = path.join(__dirname, project.toString(), 'apps.import.json')
    fsExtra.readJson(appLib, (err, data) => {
      fsExtra.emptyDirSync(`src/project/${project}/apps`)
      let apps = []
      if (data) {
        chalkTag.info(project + '加载业务应用配置...')
        Promise.all([
          findApp(`src/project/${project}`, file => {
            let reg = new RegExp(/.+[\\\/](App[^\\\/]+)$/)
            if (reg.test(file)) {
              data[file.replace(reg, '$1')] = file.replace(reg, '$1')
            }
            return apps.push(file)
          }),
          findApp('src/mods', file => apps.push(file))
        ]).then(() => Promise.all(Object.keys(data).map(e => {
          let app = [...new Set(apps)].find(s => s.indexOf(e) > -1)
          if (app) {
            return copyFiles(`src/project/${project}/apps/${e}`, app)
          }
        }))).then(() => {
          chalkTag.done(project + '业务应用加载完成')
          resolve()
        })
      } else {
        chalkTag.done(project + '业务应用无打包')
        resolve()
      }
    })
  })
  return Promise.all([getApps])
}
const start = () => {
  //询问打包哪个项目
  init().then(choices => {
    return Promise.all(choices.map(prj => generateMain(prj))).then(() => {
      chalkTag.info('开始发布...')
    })
  })
}
start();
