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

@UserStore = Reflux.createStore(
  {
    user: null

    listenables: @UserActions

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

    onAppInit: (@app) ->
      if !@user?
        @loadAnonymousUser()

    loadAnonymousUser: () ->
      @user = {id: null, has_redeemable_jamtrack: context.JK.currentUserFreeJamTrack, purchased_jamtracks_count:0, show_free_jamtrack: context.JK.currentUserFreeJamTrack }
      @changed()

    postProcess: () ->
      if @user.user_authorizations?
        for auth in @user.user_authorizations
          if auth.provider == 'stripe_connect'
            if !auth.token_expiration || new Date(auth.token_expiration).getTime() > new Date().getTime()
              @user.stripe_auth = auth


    onLoaded:(user) ->
      @user = user
      @changed()

    onModify: (changes) ->
      @user = $.extend({}, @user, changes)
      @changed()

    onRefresh: () ->
      rest.getUserDetail().done((response) => @onLoaded(response)).fail((jqXHR) => @onUserFail(jqXHR))

    onUserFail:(jqXHR) ->
      @app.layout.notify({title: 'Unable to Update User Info', text: "We recommend you refresh the page."})

    changed:() ->
      @postProcess()
      @trigger({user: @user})

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