context = window
logger = context.JK.logger
if context.JK.Rest
  rest = new context.JK.Rest()
else
  rest = context.JK.Rest2


@ConfigStore = Reflux.createStore(
  {
    top_message: null
    event_page_top_logo_url: null

    # this path taken on event landing p age
    listenables: @ConfigActions

    onConfigInit: () ->
      @fetch(0)

    init: ->
      # context.AppStore not available in landing pages.  This path below is for the /client view
      if context.AppStore
        this.listenTo(context.AppStore, this.onAppInit)

    process: (response) ->
      @top_message = response.top_message
      @event_page_top_logo_url = response.event_page_top_logo_url
      @changed()

    fetch: (wait) ->
      setTimeout((() =>
        result = rest.getConfigClient()
        if result.done
          result.done((response) =>
            @process(response)
          )
          .fail((jqXHR) =>
            console.log("failed to fetch config")
          )
        else # fetch style
          result
            .then((response) =>
              if !response.ok
                throw Error(response.statusText)
              else
                return response.json()
            )
            .then((response) =>
              @process(response)
            )
            .catch((jqXHR) =>
              console.log("failed to fetch config")
            )

      ), wait)

    onAppInit: (@app) ->
      @fetch(2000)

    changed:() ->
      @trigger({top_message: @top_message, event_page_top_logo_url: @event_page_top_logo_url})

  }
)
