/**
 * npm操作在这个文件维护
 */
const { default: axios } = require('axios')
const chalk = require('chalk')
const cp = require('child_process')
const { NPM } = require('../constant/cli')

const BASE_URL = 'https://registry.npmjs.org' // NPM 请求地址

/**
 * 执行npm命令(兼容mac和windows)。
 * @example npm(['install', 'vue','-D'])
 * @param {array} params
 * @param {object} options
 * @returns 子进程
 */
function npm(params, options) {
  return new Promise((resolve) => {
    const res = cp.spawnSync(NPM, params, {
      stdio: 'inherit',
      cwd: process.cwd(),
      ...options,
    })
    resolve(res)
  })
}

// 判断传入的名字是否是npm包维护者的
async function isNpmMaintainer(npm, name) {
  const url = `${BASE_URL}/${npm}`
  let result
  try {
    result = await axios.get(url)
  } catch (e) {
    console.log(chalk.red(`npm上无法查询到 ${npm} 这个包`))
    console.log('')
    return false
  }

  if (result.status === 200) {
    const maintainers = result.data.maintainers
    return maintainers.some((maintainer) => maintainer.name === name)
  } else {
    console.log(`请求npm接口出现${result.status}出错`, result)
    return false
  }
}

// 获取包的最新版本号
async function getPackageLatestVersion(npm) {
  const url = `${BASE_URL}/${npm}`
  const result = await axios.get(url)
  if (result.status === 200) {
    const latestVersion = result.data['dist-tags'].latest
    return latestVersion
  } else {
    console.log(`请求npm接口出现${result.status}出错`, result)
    return ''
  }
}

module.exports = {
  isNpmMaintainer,
  npm,
  getPackageLatestVersion,
}
