     ,100
     @_writeState()
     @trigger()
+
+NylasSyncWorker.BackoffTimer = BackoffTimer

    false

  start: ->
    @_resumeTimer = setInterval(@resumeFetches, 20000)
    @_connection.start()
    @resumeFetches()

  cleanup: ->
    clearInterval(@_resumeTimer)
    @_connection.end()
    @_terminated = true
    @

  resumeFetches: =>
    return unless @_state
    @fetchCollection('threads')
    @fetchCollection('calendars')
    @fetchCollection('contacts')

CoffeeHelpers = require './coffee-helpers'

PAGE_SIZE = 250

# BackoffTimer is a small helper class that wraps setTimeout. It fires the function
# you provide at a regular interval, but backs off each time you call `backoff`.
#
class BackoffTimer
  constructor: (@fn) ->
    @reset()
    @start()

  cancel: =>
    clearTimeout(@_timeout) if @_timeout
    @_timeout = null

  reset: =>
    @cancel()
    @_delay = 20 * 1000

  backoff: =>
    @_delay = Math.min(@_delay * 1.4, 5 * 1000 * 60) # Cap at 5 minutes
    console.log("Backing off after sync failure. Will retry in #{Math.floor(@_delay / 1000)} seconds.")

  start: =>
    clearTimeout(@_timeout) if @_timeout
    @_timeout = setTimeout =>
      @_timeout = null
      @fn()
    , @_delay


module.exports =
class NylasSyncWorker
