const project = require('../../project')
const { exec } = require('../../utils/shell')
const { NPM_TBSOURCE, NPM_NPMSOURCE, NPM_VVSOURCE, NPM_PACKAGE_PRINAME } = require('../../constants')

/*
* 切换npm至淘宝源
*/
async function tbsource(op) {
    let cwd = project.fs.rootDir()
    let cmd = `${op} config set registry ${NPM_TBSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fail(`${op} 切换淘宝源失败`)
        console.fatal(e.message)
    }
}

/*
* 切换npm至官方源
*/
async function npmsource(op) {
    let cwd = project.fs.rootDir()
    let cmd = `${op} config set registry ${NPM_NPMSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fail(`切换${op}官方源失败`)
        console.fatal(e.message)
    }
}

/*
* 配置 @xupd-design 私库拉取对应的源
*/
async function configVVNpmRegistry() {
    let cwd = project.fs.rootDir()
    let cmd = `npm config set ${NPM_PACKAGE_PRINAME}:registry ${NPM_VVSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
        console.ok(`关联${NPM_PACKAGE_PRINAME}至私有库地址`)
    } catch (e) {
        console.fail(`关联${NPM_PACKAGE_PRINAME}私有库地址失败`)
        console.fatal(e.message)
    }
}

/*
* 切换npm至微微私有源
*/
async function vvsource(op) {
    let cwd = project.fs.rootDir()
    let cmd = `${op} config set registry ${NPM_VVSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fail(`切换${op}源失败`)
        console.fatal(e.message)
    }
}

async function changeSource(ori, options) {
    try {
        const type = options.type
        switch (type && type.toLowerCase()) {
            case 'tb':
                await tbsource(ori)
                break
            case 'org':
                await npmsource(ori)
                break
            case 'vv':
                await vvsource(ori)
                break
            default:
                console.fatal('Invalid type: ' + type)
        }
    } catch (e) {
        console.fatal(`${ori} 源切换失败:`, e)
    }
}

async function changeNpmSource(options) {
    changeSource("npm", options)
}

async function changeYarnSource(options) {
    changeSource("yarn", options)
}

module.exports = { changeNpmSource, changeYarnSource, configVVNpmRegistry }