
context = window

console.log(@EventActions)
console.log(window.EventActions)

@EventStore = Reflux.createStore(
  {
    listenables: window.EventActions

    events: null
    eventsError: null
    eventStorage: null
    AuthorizedEventsStorage: null

    init: ->
      @AuthorizedEventStorage = context.JK.AuthorizedEventStorage

    changed: () ->
      state = @getState()
      @trigger(state)

    addAuthorization: (authorization) ->
      @AuthorizedEventStorage.storeAuthorizedEvent(authorization)
      @collateEvents()

    onRefresh: () ->
      context.JK.Rest2.listLiveStreams().then((response) => response.json()).then((response) => @refreshDone(response)).catch((jqXHR) => @refreshFailed(jqXHR))

    onSingle: (slug) ->
      context.JK.Rest2.getLiveStream(slug).then((response) => response.json()).then((response) =>
        console.log("single", response)
        if(response.errors)
          @refreshFailed(response)
        else
          matchedFormat = {entries:[ response ]}
          @refreshDone(matchedFormat))

      .catch((jqXHR) => @refreshFailed(jqXHR))

    refreshDone: (events) ->

      @eventsError = false
      @events = events
      @collateEvents()

    refreshFailed: (events) ->
      console.log("events error", events)
      @eventsError = true
      @changed()

    collateEvents: () ->
      authorizedEvents = @AuthorizedEventStorage.listAuthorizedEvents()

      for event in @events.entries

        authorization = authorizedEvents[event.id]
        if authorization
          console.log("event is authorized", event)
          event.authorization = authorization
        else
          event.authorization = null

      @changed()

    getState:() ->
      {events: @events, events_error: @eventsError}

  }
)
