/**
 * npm操作在这个文件维护
 */
import axios from 'axios'
import chalk from 'chalk'
import cp from 'child_process'
import { NPM } from '../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 子进程
 */
export function npm(params: Array<string>, options: object = {}) {
  return new Promise((resolve) => {
    const res = cp.spawnSync(NPM, params, {
      stdio: 'inherit',
      cwd: process.cwd(),
      ...options,
    })
    resolve(res)
  })
}

// 判断传入的名字是否是npm包维护者的
export async function isNpmMaintainer(npm: string, name: string) {
  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: any) => maintainer.name === name)
  } else {
    console.log(`请求npm接口出现${result.status}出错`, result)
    return false
  }
}

// 获取包的最新版本号
export async function getPackageLatestVersion(npm: string) {
  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 ''
  }
}

export default {
  isNpmMaintainer,
  npm,
  getPackageLatestVersion,
}
