const fs = require('fs')
const path = require('path')
const cp = require('child_process')

const appPath = path.join(__dirname, 'wechatdevtools')
const packResource = path.join(__dirname, '../Resources/package.nw')
const localCodePath = `${process.env.HOME}/Library/Application Support/微信web开发者工具/WeappCode/`

const localResourcePath = path.join(localCodePath, 'package.nw')
const newLocalResourcePath = path.join(localCodePath, 'new_package.nw')

const localResourcePackageJSON = path.join(localResourcePath, 'package.json')

function rmSync(filePath) {
  try {
    filePath = path.resolve(filePath)
    if (!fs.existsSync(filePath)) {
      return
    }

    let stat = fs.statSync(filePath)
    if (stat.isDirectory()) {
      let files = fs.readdirSync(filePath)
      if (files.length > 0) {
        for (let i = 0, len = files.length; i < len; i++) {
          rmSync(path.join(filePath, files[i]))
        }
      }
      fs.rmdirSync(filePath)
    } else {
      fs.unlinkSync(filePath)
    }

  } catch(e) {}
}

function mvSync (src, dist) {
  try {
    src = path.resolve(src)
    dist = path.resolve(dist)
    if (!fs.existsSync(src)) {
      // 源不存在，直接return
      return
    }

    if (fs.existsSync(dist)) {
      // 目标存在
      let distStat = fs.statSync(dist)
      let srcStat = fs.statSync(src)
      if (srcStat.isDirectory() && distStat.isDirectory()) {
        // 都是目录，则看目录内的文件
        let srcFiles = fs.readdirSync(src)
        for (let i = 0, len = srcFiles.length; i < len; i++) {
          mvSync(path.join(src, srcFiles[i]), path.join(dist, srcFiles[i]))
        }
        fs.rmdirSync(src)
        return
      }

      // src 是文件而 dist 是目录
      if (distStat.isDirectory()) {
        rmdirSync(dist)
      }
    }

    fs.renameSync(src, dist)
  } catch(e) {}
}

if (fs.existsSync(newLocalResourcePath)) {
  // 存在的 new_package 则表示，之前的代码包已经完整解压了，可以拷贝
  if (fs.existsSync(path.join(newLocalResourcePath, 'new_package'))
    || fs.existsSync(path.join(localResourcePath, 'new_package'))) {
    mvSync(newLocalResourcePath, localResourcePath)
  }
}

let cwd = localResourcePath
if (!fs.existsSync(cwd)
  || !fs.existsSync(localResourcePackageJSON)) {
  cwd = packResource
} else {
  let localResourceStat = fs.statSync(localResourcePackageJSON)
  let packResourceStat = fs.statSync(path.join(packResource, 'package.json'))
  if (localResourceStat.ctimeMs < packResourceStat.ctimeMs) {
    cwd = packResource
  }
}

const child = cp.spawn(appPath, ['.'], {
  cwd: cwd,
  detach: true
});
child.ref()

process.exit(0)