const fs = require('fs')
const path = require('path')
const md5 = require('md5-node')

const com = require('../com')

/* 目录结构操作，删除查询 */
const dirOperate = (req, res) => {
  let operate = req.body.operate || ''
  let timestamp = Math.floor(new Date().getTime() / 100000000) + '00000000'
  let md5Str = md5('ezijing.com' + timestamp)
  if (operate === '9') { res.status(200).json({ 'timestamp': timestamp, 'MD5-auth': md5Str }); return }
  let auth = req.headers.auth || ''
  if (auth === md5Str) {
    _executeOperate(req, res)
  } else {
    res.status(200).json({ 'msg': '没有权限，访问该接口' })
  }
}

const _executeOperate = (req, res) => {
  let dir = req.body.dir || ''
  let operate = req.body.operate || ''
  let json = {}
  json.dirPath = dir
  json.arrJson = {}
  if (operate === '2') {
    com.Directory.mkDir(dir, () => {
      json.arrJson.msg = '目录创建成功'
      res.status(200).json(json)
    })
    return
  }
  fs.stat(dir, (error, stats) => {
    if (error) {
      json.arrJson.msg = '当前目录，或文件不存在'
      /* 返回数据 */
      res.status(200).json(json)
    } else {
      if (operate === '0') { /* 删除 */
        if (stats.isFile()) {
          fs.unlink(dir, () => {
            json.arrJson.msg = '文件删除成功'
            res.status(200).json(json)
          })
        } else if (stats.isDirectory()) {
          com.Directory.rmDir(dir, () => {
            json.arrJson.msg = '目录删除成功'
            res.status(200).json(json)
          })
        }
      } else if (operate === '1') { /* 查询 */
        let pa = fs.readdirSync(dir)
        let dirStr = 'dir'
        let dirCount = 0
        let fileStr = 'file'
        let fileCount = 0
        for (let j = 0; j < pa.length; j++) {
          let elem = pa[j]
          let stat = fs.statSync(path.resolve(dir, elem))
          if (stat.isFile()) {
            json.arrJson[fileStr + (fileCount++)] = elem
          }
          if (stat.isDirectory()) {
            json.arrJson[dirStr + (dirCount++)] = elem
          }
        }
        /* 统计总个数 */
        json.count = pa.length
        /* 返回数据 */
        res.status(200).json(json)
      } else if (operate === '3') { /* 读取文件内容 */
        let data = fs.readFileSync(dir)
        /* 返回数据 */
        res.status(200).send(data)
      } else {
        res.status(200).json({ 'msg': 'operate 参数错误' })
      }
    }
  })
}

module.exports = {
  dirOperate: dirOperate
}
