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

@RetailerStore = Reflux.createStore(
  {
    retailer: null,
    teacherInvitations: null

    listenables: @RetailerActions

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

    onAppInit: (@app) ->

    onLoaded: (response) ->
      @retailer = response

      if @retailer.state
        LocationActions.selectRegion('US', @retailer.state)

      if @retailer.photo_url?
        @retailer.photo_url = @retailer.photo_url + '?cache-bust=' + new Date().getTime()

      if @retailer.large_photo_url?
        @retailer.large_photo_url = @retailer.large_photo_url + '?cache-bust=' + new Date().getTime()

      @changed()
      rest.listRetailerInvitations({id:@retailer.id}).done((response) => @onLoadedTeacherInvitations(response)).fail((jqXHR) => @onRetailerInvitationFail(jqXHR))

    onLoadedTeacherInvitations: (response) ->
      @teacherInvitations = response.entries
      @changed()

    onAddInvitation: (teacher, invitation) ->
      @teacherInvitations.push(invitation)
      @changed()

    onDeleteInvitation: (id) ->
      if @teacherInvitations?
        @teacherInvitations = @teacherInvitations.filter (invitation) -> invitation.id isnt id

      @changed()

    onRefresh: (retailerId) ->
      if !retailerId?
        retailerId = @retailer?.id
      rest.getRetailer({id: retailerId}).done((response) => @onLoaded(response)).fail((jqXHR) => @onRetailerFail(jqXHR))

    onUpdateRetailer: (retailer) ->
      @retailer = retailer
      @changed()

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

    onRetailerInvitationFail:(jqXHR) ->
      @app.layout.notify({title: 'Unable to Request Retailer Invitation Info', text: "We recommend you refresh the page."})

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

    getState:() ->
      {retailer: @retailer, teacherInvitations: @teacherInvitations}
  }
)
