const path = require('path')
const download = require('download')
const fs = require('fs-extra')
const os = require('os')
const { version } = require(path.resolve(__dirname, '../package.json'))

const buildDir = path.resolve(__dirname, '../build')

const platform = process.platform

const isMac = platform === 'darwin'

const no_symbol = true

const workspaceDir = `${path.join(__dirname, '..')}`

function getSystemInfo() {
  const platform = os.platform() // 获取操作系统平台
  const arch = os.arch() // 获取操作系统架构

  const isLinux = platform === 'linux'
  const isX86 = arch === 'x64'
  const isARM64 = arch === 'arm64'

  return {
    isLinux,
    isX86,
    isARM64,
  }
}

const getDownloadURL = () => {
  if (isMac) {
    return `https://yx-web-nosdn.netease.im/package/NERoomKit_Napi_Mac_${version}.zip`
  }

  const linuxSystemInfo = getSystemInfo()

  if (linuxSystemInfo.isLinux) {
    console.log('sss', linuxSystemInfo)
    if (linuxSystemInfo.isARM64) {
      return `https://yx-web-nosdn.netease.im/package/NERoomKit_Napi_Linux_arm64_${version}.zip`
    } else {
      return `https://yx-web-nosdn.netease.im/package/NERoomKit_Napi_Linux_x86_${version}.zip`
    }
  }

  return `https://yx-web-nosdn.netease.im/package/NERoomKit_Napi_Win_${version}.zip`
}

const macNoSymbolList = [
  './build/Release/obj.target',
  './build/Release/neroom.node.dSYM',
]

const winNoSymbolList = ['./build/Release/obj', './build/Release/neroom.pdb']

const removeFileByFilter = async () => {
  const filterList = isMac ? macNoSymbolList : winNoSymbolList

  for (const iterator of filterList) {
    const filePath = `${path.join(workspaceDir, iterator)}`

    await fs.remove(filePath)
  }
}

const downloadPrebuild = async () => {
  if (fs.existsSync(buildDir)) {
    return
  }

  const downloadUrl = getDownloadURL()

  await download(downloadUrl, buildDir, {
    strip: 1,
    extract: true,
    filter: (file) => {
      return (
        file.type !== 'directory' &&
        !file.path.endsWith(path.sep) &&
        file.data.length !== 0
      )
    },
  })

  if (no_symbol) {
    await removeFileByFilter()
  }
}

downloadPrebuild()
