const fs = require('fs')
const path = require('path')
const { cd, cp, mv, rm } = require('../../utils/shell')
const { getXupdcliPath } = require('../../utils/xupdfilePath')
const { applyProjectName } = require('../../command/init/applyProjectName')
const project = require('../../project')
const { install } = require('../../command/install')
const { configVVNpmRegistry } = require('./changeSource.js')
const { configPackageJson } = require('./package.js')
const {isMacOS} = require('../../utils/platform')
const {gradleAccessRequest} = require('../install/access')

module.exports.initNpmProject = async (projectName, options) => {
    try {
        console.printLogo()
        console.step(`创建xUPD组件项目工程`)

        const currentPath = path.normalize(process.cwd())
        const projectPath = path.resolve(currentPath, projectName)
        project.fs._setRootDir(projectPath)

        // 模板工程，资源文件地址
        let xupdCliPath = await getXupdcliPath()
        let templatePath = path.resolve(xupdCliPath, "template/npm_template")

        if (!/^[a-zA-Z0-9\-]+$/.test(projectName)) {
            console.fatal('名字中只能包含英文字符')
        }

        await rm('-rf', projectPath) // For Debug
        if (fs.existsSync(projectPath)) {
            console.fatal(`目录"${projectPath}"已经存在`)
        }

        // 下载主工程文件
        await cd(currentPath)
        console.spin()

        await cp('-rf', templatePath, projectName)
        // 修改模板名称
        await applyProjectName("XcodeTemplateProject", projectName.replace(/-/g,""))
        // 配置组件模板 package.json 文件
        await configPackageJson(projectName)

        // 配置npm私有源
        await configVVNpmRegistry()

        console.log()
        console.log(`项目工程"${projectName}"创建成功!`)
        console.log()



        if (options.skipInstall) {
            console.log(`请执行命令"cd ${projectName} && xupd install"安装需要的依赖库`)
            console.log()
        } else {
            await install({ silent: true })
        }
        if (isMacOS()) {
            let gradlew = project.fs.resolve('example/android/gradlew')
            await gradleAccessRequest(gradlew)
        }
    } catch (e) {
        if (e.type !== 'shell') {
            console.error('[失败] ' + e.message)
        }
        console.debug(e)
    }
}
