 util  = require 'util'
 aws   = require 'aws2js'
 
-# sets up hooks to persist the brain into redis.
 module.exports = (robot) ->
 
   loaded            = false
   key               = process.env.HUBOT_S3_BRAIN_ACCESS_KEY_ID
   secret            = process.env.HUBOT_S3_BRAIN_SECRET_ACCESS_KEY
   bucket            = process.env.HUBOT_S3_BRAIN_BUCKET
+  # default to 30 minutes (in seconds)
+  save_interval     = process.env.HUBOT_S3_BRAIN_SAVE_INTERVAL || 30 * 60
   brain_dump_path   = "#{bucket}/brain-dump.json"
 
   if !key && !secret && !bucket
     throw new Error('S3 brain requires HUBOT_S3_BRAIN_ACCESS_KEY_ID, ' +
       'HUBOT_S3_BRAIN_SECRET_ACCESS_KEY and HUBOT_S3_BRAIN_BUCKET configured')
+
+  save_interval = parseInt(save_interval)
+  if isNaN(save_interval)
+    throw new Error('HUBOT_S3_BRAIN_SAVE_INTERVAL must be an integer')
 
   s3 = aws.load('s3', key, secret)
 

#   "aws2js": "0.7.10"
#
# Configuration:
#   HUBOT_S3_BRAIN_ACCESS_KEY_ID
#   HUBOT_S3_BRAIN_SECRET_ACCESS_KEY
#   HUBOT_S3_BRAIN_BUCKET
#
# Commands:
#
# Notes:
#   It's highly recommended to use an IAM account explicitly for this purpose
#   https://console.aws.amazon.com/iam/home?
#   A sample S3 policy for a bucket named Hubot-Bucket would be


  robot.brain.on 'loaded', () ->
    loaded = true
    robot.brain.resetSaveInterval(save_interval)
    store_current_brain()

  robot.brain.on 'save', () ->
    store_current_brain()

  robot.brain.on 'close', ->
    store_current_brain()
