$ = jQuery
context = window
logger = context.JK.logger
broadcastActions = @BroadcastActions
SessionActions = @SessionActions

rest = context.JK.Rest()

broadcastActions.load.listenAndPromise(rest.getBroadcastNotification);

BroadcastStore = Reflux.createStore(
  {
    listenables: broadcastActions

    currentSession: null
    currentLesson: null
    broadcast: null
    currentLessonTimer: null
    teacherFault: false
    isJamClass: false
    sessionRules: null
    subscriptionRules: null
    subscriptionConcern: null
    currentSubscriptionTimer: null
    init: ->
      this.listenTo(context.AppStore, this.onAppInit)
      this.listenTo(context.SessionStore, this.onSessionChange)
      this.listenTo(context.NavStore, this.onNavChange)

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

    lessonTick: () ->
      @timeManagement()
      @changed()

    subscriptionTick: () ->
      @subscriptionManagement()
      @changed()

    openBrowserToPayment: () ->
      context.JK.popExternalLink("/client#/account/subscription", true)

    openBrowserToPlanComparison: () ->
      context.JK.popExternalLink("https://jamkazam.freshdesk.com/support/solutions/articles/66000122535-what-are-jamkazam-s-free-vs-premium-features-")
      return 'noclose'

    subscriptionManagement: () ->
      @subscriptionConcern.until = @lessonUtils.getTimeRemaining(@subscriptionConcern.main_concern_time)
      if @session?.participants.length > 1 && @subscriptionConcern.until.total < -30000
        leaveBehavior =
          location: "/client#/findSession"
        buttons = []
        buttons.push({name: 'CLOSE', buttonStyle: 'button-grey'})
        buttons.push({name: 'COMPARE PLANS', buttonStyle: 'button-grey', click: (() => (@openBrowserToPlanComparison()))})
        buttons.push({
          name: 'UPGRADE PLAN',
          buttonStyle: 'button-orange',
          click: (() => (@openBrowserToPayment()))
        })

        if @subscriptionConcern.main_concern_type == "remaining_month_play_time"
          context.JK.Banner.show({
            title: "Out of Time For This Month",
            html: context._.template($('#template-no-remaining-month-play-time').html(), {}, { variable: 'data' }),
            buttons: buttons});
        else
          context.JK.Banner.show({
            title: "Out of Time For This Session",
            html: context._.template($('#template-no-remaining-session-play-time').html(), {}, { variable: 'data' }),
            buttons: buttons});

        SessionActions.leaveSession.trigger(leaveBehavior)


    timeManagement: () ->
      lastCheck = $.extend({}, @currentLesson)
      lessonSession = @currentLesson
      lessonSession.until = @lessonUtils.getTimeRemaining(lessonSession.scheduled_start)
      if lessonSession.until.total < 0
        # we are past the start time
        if lessonSession.until.total > -(10 * 60 * 1000) # 10 minutes
          lessonSession.initialWindow = true
        else
          lessonSession.initialWindow = false
        lessonSession.beforeSession = false
      else
        # we are before the due time
        lessonSession.initialWindow = false
        lessonSession.beforeSession = true

      # if we've transitioned to a new window

      if !lessonSession.beforeSession && ((lastCheck.initialWindow || !lastCheck.initialWindow?) && !lessonSession.initialWindow)
        logger.debug("BroadcastStore: lesson session 'initial window' transition")
        rest.getLessonAnalysis({id: lessonSession.id}).done((response) => @lessonAnalysisDone(response)).fail(@app.ajaxError)

    lessonAnalysisDone: (@analysis) ->

      if !@currentLesson?
        logger.debug("BroadcastStore: ignoring lessonAnalysisDone")
        return

      if @analysis.status == 'completed'
        logger.debug("BroadcastStore: lesson is over")
        @currentLesson.completed = true
        @currentLesson.success = @analysis.success
        @clearLessonTimer()
        @changed()
      else if @analysis.analysis.reason != 'teacher_fault'
        logger.debug("BroadcastStore: not teacher fault; clearing lesson info")
        @clearLesson()
      else
        logger.debug("BroadcastStore: teacher is at fault")
        @teacherFault = true
        @clearLessonTimer()
        @changed()

    clearLesson: () ->
      if @currentLesson?
        @currentLesson = null
      @clearLessonTimer()
      @teacherFault = false
      @changed()

    clearSubscription: () ->
      @subscriptionConcern = null
      @clearSubscriptionTimer()
      @changed()

    clearLessonTimer: () ->
      if @currentLessonTimer?
        clearInterval(@currentLessonTimer)
        @currentLessonTimer = null

    clearSubscriptionTimer: () ->
      if @currentSubscriptionTimer?
        clearInterval(@currentSubscriptionTimer)
        @currentSubscriptionTimer = null

    onNavChange: (nav) ->
      path = nav.screenPath.toLowerCase()
      @isJamClass = path.indexOf('jamclass') > -1 || path.indexOf('teacher') > -1
      @changed()

    onSessionChange: (session) ->

      @session = session
      currentSession = session.session
      if currentSession? && session.inSession()
        @subscriptionRules = session.subscriptionRules
        @sessionRules = session.sessionRules

        if @subscriptionRules

          if !@subscriptionRules.remaining_month_until? && !@sessionRules.remaining_session_until?
            console.log("no license issues")
            @subscriptionConcern = null
          else
            @subscriptionConcern = {}
            @subscriptionConcern.participants = @session?.participants().length
            if !@subscriptionRules.remaining_month_until?
              @subscriptionConcern.main_concern_time = @sessionRules.remaining_session_until
              @subscriptionConcern.main_concern_type = "remaining_session_play_time"
            else if !@sessionRules.remaining_session_play_time?
              @subscriptionConcern.main_concern_time = @subscriptionRules.remaining_month_until
              @subscriptionConcern.main_concern_type = "remaining_month_play_time"
            else
              if @sessionRules.remaining_session_play_time < @subscriptionRules.remaining_month_play_time
                @subscriptionConcern.main_concern_time = @sessionRules.remaining_session_until
                @subscriptionConcern.main_concern_type = "remaining_session_play_time"
              else
                @subscriptionConcern.main_concern_time = @subscriptionRules.remaining_month_until
                @subscriptionConcern.main_concern_type = "remaining_month_play_time"

            @subscriptionManagement()
            #logger.debug("BroadcastStore: session can play until: ", @subscriptionConcern.until, @subscriptionConcern.main_concert_time)
            if !@currentSubscriptionTimer?
              @currentSubscriptionTimer = setInterval((() => @subscriptionTick()), 1000)
            @changed()

        if currentSession.lesson_session?
          @currentSession = currentSession

          lessonSession = currentSession.lesson_session
          # so that receivers can check type of info coming at them via one-way events
          lessonSession.isLesson = true

          if lessonSession.status == 'completed'
            lessonSession.completed = true
            lessonSession.success = lessonSession.success
          #else
          #  rest.getLessonAnalysis({id: lessonSession.id}).done((response) => @lessonAnalysisDone(response)).fail(@app.ajaxError)

          @currentLesson = lessonSession
          @timeManagement()
          logger.debug("BroadcastStore: currentLesson until: ", @currentLesson.until, lessonSession.scheduled_start)
          if !@currentLessonTimer?
            @currentLessonTimer = setInterval((() => @lessonTick()), 1000)
          @changed()
      else
        @clearLesson()
        @clearSubscription()

    onLoad: () ->
      logger.debug("loading broadcast notification...")

    onLoadCompleted: (response) ->
      if response.id?
        logger.debug("broadcast notification sync completed")
        @broadcast = response
        @changed()


    onLoadFailed: (jqXHR) ->
      if jqXHR.status != 404
        logger.error("broadcast notification sync failed")

    onHide: () ->
      @broadcast = null
      @changed()

    changed: () ->
      if @subscriptionConcern?
        this.trigger({subscriptionConcern: @subscriptionConcern})
      else
        this.trigger(null)
  }
)

context.JK.Stores.Broadcast = BroadcastStore

