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

/**
 * 删除目录，对应下面所有文件
 * @param {[string]} dirPath 目录路径字符串
 * @param {[function]} callback 删除成功或者失败时，回调函数
 */
const rmDir = (dirPath, callback) => {
  fs.readdir(dirPath, (err, files) => {
    if (err) { console.log(err) }
    function next (index) {
      if (index === files.length) return fs.rmdir(dirPath, callback)
      let newPath = path.join(dirPath, files[index])

      fs.stat(newPath, (err, stat) => {
        if (err) { console.log(err) }
        if (stat.isDirectory()) {
          rmDir(newPath, () => next(index + 1))
        } else {
          fs.unlink(newPath, () => next(index + 1))
        }
      })
    }
    next(0)
  })
}

/**
 * 创建目录路径上所有目录，不存在则创建
 * @param {[string]} dirPath 目录路径字符串
 * @param {[function]} callback 删除成功或者失败时，回调函数
 */
const mkDir = (dirPath, callback) => {
  let _path = path.resolve(dirPath).replace(/^\//gi, '')
  let arrDir = _path.split('/')
  let curPath = '/'
  function next (index) {
    if (index === arrDir.length) { callback && callback(); return }
    curPath += arrDir[index] + '/'
    fs.stat(curPath, (error, stats) => {
      if (error || !stats.isDirectory()) {
        fs.mkdir(curPath, (error) => {
          if (error) { console.log('文件创建出错，可能没权限'); return }
          next(index + 1)
        })
      } else {
        next(index + 1)
      }
    })
  }
  next(0)
}

module.exports = {
  rmDir: rmDir,
  mkDir: mkDir
}
