var fs = require('fs')
const project = require('../../project')
const { exec } = require('../../utils/shell')
const { npmlogin } = require('./login.js')
const { rm } = require('../../utils/shell')
const { NPM_TBSOURCE, NPM_NPMSOURCE, NPM_VVSOURCE } = require('../../constants')

async function publish(options) {
    let npmSource = ''
    const type = options.type
    switch (type && type.toLowerCase()) {
        case 'tb':
            npmSource = NPM_TBSOURCE
            break
        case 'org':
            npmSource = NPM_NPMSOURCE
            break
        case 'vv':
            npmSource = NPM_VVSOURCE
            break
        default:
            console.fatal('Invalid type: ' + type)
    }

    let cwd = project.fs.rootDir()
    let cmd = `npm version patch && npm --registry=${npmSource} publish`
    try {
        await exec(`${cmd}`, { cwd })
        console.ok('npm 组件发布成功')
    } catch (e) {
        console.fail("npm 组件发布失败")
        console.fatal(e.message)
    }
}

async function compile() {
    let cwd = project.fs.rootDir()
    let libPath = project.fs.resolve("lib")
    await rm('-rf', libPath)

    let cmd = `yarn compile`
    try {
        await exec(`${cmd}`, { cwd })
        console.ok('npm 组件编译成功')
    } catch (e) {
        console.fail("npm 组件编译失败")
        console.fatal(e.message)
    }
}

async function npmyarn() {
    let cwd = project.fs.rootDir()
    let cmd = "yarn"
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fatal(e.message)
    }
}

async function changeToVVSource() {
    let cwd = project.fs.rootDir()
    let cmd = `npm config set registry ${NPM_VVSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fatal(e.message)
    }
}

async function changeToTBSource() {
    let cwd = project.fs.rootDir()
    let cmd = `npm config set registry ${NPM_TBSOURCE}`
    try {
        await exec(`${cmd}`, { cwd })
    } catch (e) {
        console.fatal(e.message)
    }
}

module.exports.npmPublish = async (options) => {
    await npmyarn()
    // await compile()
    await changeToVVSource()
    await npmlogin(options)
    await publish(options)
    await changeToTBSource()
}