const project = require('../../project')
const { exec } = require('../../utils/shell')
const { isMacOS, isWindows } = require('../../utils/platform')
const outputFilter = (type, data) => {
    if (type === 'stdout') {
        if (!/^\s/.test(data)) {
            process.stdout.write(data)
        }
    } else {
        process.stderr.write(data)
    }
}

async function bundleForIOS(options) {
    console.step('打包 iOS Bundle')
    console.spin()

    if (project.fs.exists('Release_ios/Assets')) {
        await project.fs.rm('Release_ios/Assets')
    }
    await project.fs.mkdir('Release_ios/Assets')

    await exec('npx react-native bundle --platform ios --dev false '
        + (options.resetCache ? '--reset-cache ' : '')
        + '--entry-file index.js '
        + '--bundle-output Release_ios/Assets/main.jsbundle '
        + '--assets-dest Release_ios/Assets',
        {
            cwd: project.fs.rootDir(),
            outputFilter,
        })
    console.ok('iOS Bundle 打包成功')
}

async function bundleForAndroid(options) {
    console.step('打包 Android Bundle')
    console.spin()
    const projectName  = await project.config.getProjectName()
    const libName = `lib_${projectName.toString().toLowerCase()}`
    await exec("npx react-native bundle --platform android --dev false "
        + (options.resetCache ? "--reset-cache " : "")
        + "--entry-file index.js "
        + `--bundle-output android/${libName}/src/main/assets/index.android.bundle `
        + `--assets-dest android/${libName}/src/main/res/`,
        {
            cwd: project.fs.rootDir(),
            outputFilter,
        })
    console.ok('Android Bundle 打包成功')
}

async function bundle(options) {
    try {
        const platform = options.platform
        switch (platform && platform.toLowerCase()) {
            case 'ios':
                await bundleForIOS(options)
                break
            case 'android':
                await bundleForAndroid(options)
                break
            case 'all':
                if (isMacOS()) {
                    await bundleForIOS(options)
                }
                await bundleForAndroid(options)
                break
            default:
                console.fatal('Invalid platform: ' + platform)
        }
    } catch (e) {
        console.fatal('Bundle 打包失败:', e)
    }
}

module.exports = { bundle }
