 _          = require 'lodash'
-async       = require 'async'
+async      = require 'async'
+debug      = require('debug')('interval-service')
 cronParser = require 'cron-parser'
-debug      = require('debug')('interval-service')
 
 class KueWorker
   constructor: (dependencies={})->
+    @INTERVAL_TTL       = process.env.INTERVAL_TTL ? 10000
+    @INTERVAL_JOBS      = process.env.INTERVAL_JOBS ? 1000
+    @INTERVAL_ATTEMPTS  = process.env.INTERVAL_ATTEMPTS ? 999
     @INTERVAL_PROMOTION = process.env.INTERVAL_PROMOTION ? 100
-    @INTERVAL_JOBS      = process.env.INTERVAL_JOBS ? 1000
 
     @kue = dependencies.kue ? require 'kue'
     IORedis = dependencies.IORedis ? require 'ioredis'

    parser = cronParser.parseExpression cronString, currentDate: currentDate

    while timeDiff <= 0
      nextTime = parser.next()
      nextTime.setMilliseconds 0
      timeDiff = nextTime - currentDate
      debug 'this is the next time', timeDiff, nextTime.getTime()

    return timeDiff

  setCronInterval: (intervalTime, cronString) =>
    return unless intervalTime? and cronString?
    @redis.set "interval/time/#{job.data.targetId}", intervalTime

module.exports = KueWorker

        debug 'creating a new job!'
        @meshbluMessage.message [job.data.targetId], timestamp: Date.now()

        if cronString?
          try
            intervalTime = @calculateNextCronInterval cronString, jobStartTime
            @redis.set "interval/time/#{job.data.targetId}", intervalTime
          catch error
            console.error error
            done()

        @createJob(job, intervalTime).
          save (err) =>
            debug 'created a job', job.id
            redis.sadd "interval/job/#{job.data.targetId}", job.id
            done(err)

  getTargetJobs: (job, callback=->) =>
    @redis.srem "interval/job/#{job.data.targetId}", job.id
