const { result } = require('lodash')
const path = require('path')
const fs = require('fs')
const { isMacOS, isWindows } = require('./platform')
const { exec } = require('./shell')
const project = require('../project')

/**
 * 获取xupd-cli命令绝对路径
 */
async function getXupdcliPath() {
    let xupdCmd = `where xupd`
    if (isMacOS()) {
        xupdCmd = `which xupd`
    }
    let xupdCliPath = undefined
    try {
        let result = await exec(`${xupdCmd}`, {
            silent: true
        })

        if (isMacOS()) {
            xupdCliPath = result.stdout.replace("\n", "").replace("\r", "").replace("bin/xupd", "").concat("lib/node_modules/xupd-cli/")
        } else if (isWindows()) {
            let index = result.stdout.indexOf("\n")
            xupdCliPath = path.normalize(result.stdout.substring(0, index).replace("\r", "").replace("xupd", "").concat("node_modules/xupd-cli/"))
        }
        return xupdCliPath
    } catch (e) {
        if (result && result.stderr) {
            console.log(result.stderr)
        }
        console.fatal(e.message)
    }
}

/*
* 获取Podfile文件路径
* 项目模板位于 ios/Podfile
* 组件模板位于 example/ios/Podfile
*/
async function getPodFilePath() {
    let podPath = project.fs.resolve('example/ios/Podfile')
    if (fs.existsSync(podPath) == false) {
        podPath = project.fs.resolve('ios')
    } else {
        podPath = project.fs.resolve('example/ios')
    }
    return podPath
}

/*
* 获取yarn 安装路径
* 项目模板位于 ios
* 组件模板位于 example
*/
async function getYarnPath() {
    let yarnPath = project.fs.resolve('example/ios/Podfile')
    if (fs.existsSync(yarnPath) == false) {
        yarnPath = project.fs.rootDir()
    } else {
        yarnPath = project.fs.resolve('example')
    }
    return yarnPath
}

module.exports = {
    getXupdcliPath,
    getPodFilePath,
    getYarnPath
}
