const pdf = require('pdf-parse')
const fs = require('fs')
const readline = require('readline')
const AdmZip = require('adm-zip') // 引入查看zip文件的包

function parseTxt (file) {
  return new Promise((resolve, reject) => {
    let input = fs.createReadStream(file)
    const rl = readline.createInterface({
      input
    })
    let conts = ''
    rl.on('line', (input) => {
      conts += input
    })
    rl.on('close', (input) => {
      resolve(conts)
    })
  })
}

function parseDocx (filePath) {
  const zip = new AdmZip(filePath) // filePath为文件路径
  let contentXml = zip.readAsText('word/document.xml')// 将document.xml读取为text内容
  let str = ''
  contentXml.match(/<w:t>[\s\S]*?<\/w:t>/ig).forEach((item) => {
    str += item.slice(5, -6)
  })
  return Promise.resolve(str)
}

function parsePdf (filePath) {
  return new Promise((resolve, reject) => {
    let dataBuffer = fs.readFileSync(filePath)
    pdf(dataBuffer).then(function (data) {
      resolve(data.text)
    })
  })
}

module.exports.parseResume = function (file) {
  let filePath = file.path
  let fileName = file.name
  if (/\.txt$/.test(fileName)) {
    return parseTxt(filePath)
  } else if (/\.(docx)$/.test(fileName)) {
    return parseDocx(filePath)
  } else if (/\.(pdf)$/.test(fileName)) {
    return parsePdf(filePath)
  } else {
    return {}
  }
}
