import * as path from 'path'
import { exec, execSync } from 'child_process'

const base = path.resolve(__dirname, '..', 'bin')

/**
 * binary文件位置信息
 * @type {{win32, darwin, linux}}
 */
export const ADB_BINARY_FILE: {
  [key: string]: string
} = {
  win32: path.resolve(base, 'window/adb.exe'),
  darwin: path.resolve(base, 'mac/adb'),
  linux: path.resolve(base, 'linux/adb'),
}

export function isSystemAdbAvailable() {
  let systemAdbExist: boolean = false
  try {
    const output = execSync('adb --version')
    const result = output.toString()
    if (result.toLowerCase().includes('version')) {
      systemAdbExist = true
    }
  } catch (e) {
    systemAdbExist = false
  }

  return systemAdbExist
}

/**
 * 执行adb命令
 *
 * @param command {string} adb命令
 * @param option  {object} 配置exec启动进程的选项
 * @returns {Promise<String, Error>} 成功时返回stdout输出， 执行失败返回Error对象
 */
export function execADBCommand(command: string, option?: object) {
  let execCmd = command
  if (!isSystemAdbAvailable()) {
    let cmd = command.split(' ')
    const binFile = ADB_BINARY_FILE[process.platform]
    cmd[0] = `"${binFile}"`
    execCmd = cmd.join(' ')
  }

  return new Promise((resolve, reject) => {
    exec(execCmd, option || { stdio: 'inherit' }, (err, stdout, stderr) => {
      console.log(err, stdout, stderr)
      if (err) {
        reject(err)
      }
      resolve(stdout)
    })
  }).catch(err => {
    return err
  })
}
