$ = jQuery
context = window
logger = context.JK.logger
rest = new context.JK.Rest()

@LessonTimerStore = Reflux.createStore(
  {
    listenables: @LessonTimerActions
    lessons: {}
    slowTime: 10000
    fastTime: 1000

    init: ( ) ->
      @timer()
      this.listenTo(context.AppStore, this.onAppInit)

    onAppInit: (@app) ->
      @lessonUtils = context.JK.LessonUtils

    timer: () ->
      setInterval((() => @timeout()), @fastTime)

    onLoadLessons: (lessons) ->
      for lesson in lessons?.entries
        @lessons[lesson.id] = lesson

    timeout: () ->

      for id, lesson of @lessons
        untilInfo = @lessonUtils.getTimeRemaining(lesson.music_session.scheduled_start)

        initialWindow = false
        inThePast = false
        beforeSession = false
        startingSoon = false
        lessonWindow = false

        if untilInfo.total < 0
            # we are past the start time
          if -untilInfo.total < (10 * 60 * 1000) # 10 minutes
            initialWindow = true
          if -untilInfo.total < (lesson.duration*60*1000) # duration
            inThePast = true
        else
          # we are before the due time
          beforeSession = true
          startingSoon = untilInfo.total <= (60 * 60 * 1000) # 60 minutes - 1hr until start time

        lesson.times = {until:untilInfo, initialWindow: initialWindow, beforeSession: beforeSession, startingSoon: startingSoon, inThePast: inThePast}

      @changed()

    changed:() ->
      this.trigger(@lessons)
  }
)