const {exec} = require('../../utils/shell')
const project = require('../../project')
const {isMacOS} = require('../../utils/platform')
const {getPodFilePath, getYarnPath} = require('../../utils/xupdfilePath')
const {gradleAccessRequest} = require('../install/access')
// 安装npm 依赖
const installYarn = async (options) => {
    console.step('安装NPM依赖')
    console.spin()
    let result
    let yarnPath = await getYarnPath()
    try {
        result = await exec(`yarn install --cwd "${yarnPath}"`, {
            silent: !!options.silent
        })
        console.ok('NPM依赖安装完成')
    } catch (e) {
        if (result && result.stderr) {
            console.log(result.stderr)
        }
        console.fatal(e.message)
    }
}

// 安装cocoaPod依赖
const installCocoaPods = async (options) => {
    console.step('安装CocoaPods依赖')
    console.spin()
    let result
    let podPath = await getPodFilePath()
    try {
        result = await exec(`cd ${podPath} && pod install`, {
            silent: !!options.silent
        })
        console.ok('CocoaPods依赖安装完成')
    } catch (e) {
        if (result && result.stderr) {
            console.log(result.stderr)
        }
        console.fatal(e.message)
    }
}

// 安装gradle依赖
const installGradle = async () => {
}

// 安装npm&cocoapods&gradle依赖
const install = async (options) => {
    await installYarn(options)

    if (isMacOS()) { // Mac 环境
        await installCocoaPods(options)
    } else { // 其他环境
        console.warn('非 macOS 环境不支持 pod install')
    }

    await installGradle(options)

    if (isMacOS()) {
        const gradlew = project.fs.resolve('android/gradlew')
        //console.log("===Permission", gradlew)
        await gradleAccessRequest(gradlew)
    }

    console.log()
    console.log('全部依赖安装成功')
    console.log()
}


module.exports = {install}
