fs = require("fs")
path = require("path")
os = require("os")
md5 = require('MD5')
_ = require("underscore")
mkdirp = require("mkdirp").sync
MailParser = require("mailparser").MailParser
dateFormat = require("dateformat")
async = require("async")
if os.platform() is "win32"
  userHome = process.env.USERPROFILE
else
  userHome = process.env.HOME

dropboxDir = path.join(userHome,'Dropbox','CCTV','motion_clips')

mkdirp(dropboxDir)

q = async.queue((task, callback) ->
  nextJob = callback
  parser = new MailParser()
  file = task
  #console.log process.cwd()
  readFile = (next) ->
    console.log "Reading email file... #{task}"
    filePath = path.join(process.cwd(),'messages')
    fullPath = path.join filePath,file
    donePath = path.resolve filePath,"./parsed"
    doneFullPath = path.join donePath,file
    console.log fullPath
    email = fs.readFileSync fullPath
    console.log "Done reading email #{task}."
    next(null,email)

  parseFile = (email,next) ->
    console.log "parsing file..."

    parser.on "end", (mail_object) ->
      #console.log mail_object
      #console.log "done parsing file..."
      next(null,mail_object)
    parser.write email
    parser.end()

  writeImages = (msg,next) ->
    #console.log "writing files..."
    msgDate = new Date(msg.headers.date)
    #console.log msgDate
    processAttachment = (attachment, callback) ->
      fileExt = path.extname(attachment.fileName)
      fileDate = dateFormat(msgDate,'yyyy-mm-dd')
      fileTime = dateFormat(msgDate,'HHMMss')
      fileName = fileTime + "_" + md5(attachment.fileName) + fileExt
      filePath = path.join(dropboxDir,fileDate)
      mkdirp(filePath)
      fullFilePath = path.join(filePath,fileName)
      #console.log "writing image file...#{fileName}"
      fs.writeFile fullFilePath, attachment.content, (err) ->
        #console.log "done writing image file"
        callback(null)
    attachments = msg.attachments
    
    #console.log attachments
    async.eachSeries attachments, processAttachment, (err) ->
      throw err if err?
      #console.log "done with all attachments"
      next(null)
  rmFile = (callback) ->
    readFile = path.join(process.cwd(),'messages',task)
    fs.unlink(readFile,(err) ->
      throw err if err?
      callback()
    )

  async.waterfall [
    readFile
    parseFile
    writeImages
    rmFile
  ], (err,result) ->
    throw err if err?
    #console.log result
    nextJob()
, 1)

# assign a callback
q.drain = ->
  console.log "all MESSAGES have been processed"
  process.exit()
  return

fs.readdir './messages',(err,files) ->
  throw err if err?
  #console.log files
  _.each files, (file) ->
    q.push file, (err) ->
      console.log "finished processing email"
      return

