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

@LatencyStore = Reflux.createStore(
  {
    latencies: []

    listenables: @LatencyActions

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

    onAppInit: (@app) ->

    changed: () ->
      $(document).triggerHandler("user_latency_update", { users: @latencies })
      @trigger(users: { @latencies })
    
    onResolve: (user_ids) ->
      rest.getLatencyToUsers({user_ids: user_ids}).done((response) => @onLoaded(response)).fail((jqXHR) => @onLatencyFail(jqXHR, user_ids))
      
    onLoaded: (response) ->
      usersLatencies = response.users
      @latencies = @latencies.concat(usersLatencies)
      @latencies = _.uniq(@latencies)
      @changed()

    onLatencyFail:(jqXHR, user_ids) ->
      LatencyActions.fail(user_ids)

    onFail:(user_ids) ->
      logger.debug("onLatencyFail", { user_ids: user_ids })
      $(document).triggerHandler("user_latency_fail", { user_ids: user_ids })
      @trigger( { user_ids: user_ids } )

    getState:() ->
      { latencies: @latencies }
  }
)
