/**
 * 其他不好分类的工具函数在这个文件维护
 */
import path from 'path'
import cp from 'child_process'
import os from 'os'

// 让程序休眠一会
// 目前这个用于防止spinner.text覆盖掉上一次的spinner.text显示(因为短时间内多次执行spinner.text会被防抖掉)
export function sleep(timeout = 200) {
  return new Promise((resolve) => setTimeout(resolve, timeout))
}

// 兼容路径
export function formatPath(p: string) {
  if (p && typeof p === 'string') {
    const sep = path.sep // 获取路径分隔符
    if (sep === '/') {
      return p
    } else {
      return p.replace(/\\/g, '/')
    }
  }
  return p
}

/**
 * 执行指令并获取指令返回值
 * @example spawnPromise('npm',['install', 'vue','-D'], {})
 * @param {string} command
 * @param {array} args
 * @param {object} options
 * @returns
 */
export function spawnPromise(command: string, args: Array<any>, options = {}) {
  return new Promise((resolve) => {
    let output = ''

    const p = cp.spawn(command, args, options)

    p.stderr.on('data', (e: any) => {
      output = output + e.toString('utf8')
    })

    p.stdout.on('data', (e: any) => {
      output = output + e.toString('utf8')
    })

    p.on('exit', (code: any) => {
      const res = {
        code,
        output,
      }
      resolve(res)
    })
  })
}

// 在浏览器里打开地址
export function openInBrowser(url: string) {
  let cmd = ''
  switch (os.platform()) {
    case 'win32':
      cmd = 'start'
      break

    case 'linux':
      cmd = 'xdg-open'
      break

    case 'darwin':
      cmd = 'open'
      break
  }
  cp.exec(`${cmd} ${url}`)
}

export default {
  sleep,
  formatPath,
  spawnPromise,
  openInBrowser,
}
