const fs = require('fs')
const path = require('path')
const { cd, cp, mv, rm } = require('../../utils/shell')
const { getXupdcliPath } = require('../../utils/xupdfilePath.js')
const { clone } = require('../../utils/git')
const { applyProjectName } = require('./applyProjectName.js')
const project = require('../../project')
const { install } = require('../install')
const { updateResources } = require('./configPro')
const { configVVNpmRegistry } = require('../npm/changeSource.js')

module.exports.initProject = 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/cli_template")
        let resourcePath = path.resolve(xupdCliPath, "template/cli_resource")

        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 clone('direct:http://172.16.6.11:8050/xupd/tools/xupd-cli-template-project.git#master', projectName)
        await cp('-rf', templatePath, projectName)
        applyProjectName("XCODE_TEMPLATE_PROJECT", projectName) // 修改模板名称
        applyProjectName("rn_lib", `lib_${projectName.toLowerCase()}`)
        console.ok('模板工程生成成功')

        // 下载配置文件
        console.step('配置xUPD项目自定义文件')
        const resourcesPath = project.fs.resolve('resources')
        console.spin()
        // await clone('direct:http://172.16.6.11:8050/xupd/tools/xupd-cli-resourse.git#master', resourcesPath)
        await cp('-rf', resourcePath, resourcesPath)
        console.ok('配置资源下载成功')

        await cp('-rf', resourcesPath + '/*', projectPath)

        // 拷贝Podfile文件至ios目录
        const origPodfilePath = project.fs.resolve('Podfile')
        const destPodfilePath = project.fs.resolve('ios/Podfile')
        if (fs.existsSync(origPodfilePath)) {
            await mv(origPodfilePath, destPodfilePath)
        }

        // 根据项目修改原始解压文件配置
        await updateResources(projectName)

        console.ok('配置资源更新完成')

        // 删除临时资源
        await project.fs.rm(resourcesPath, '__MACOSX', '__tests__')

        // 初始化xupd配置
        await project.config.init(projectName)

        // 配置npm私有源
        configVVNpmRegistry()

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

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