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

@SessionsStore = Reflux.createStore(
  {
    listenables: SessionsActions

    my: {sessions: [], currentPage: 0, next: null, searching: false, count: 0}
    open: {sessions: [], currentPage: 0, next: null, searching: false, count: 0}
    upcoming: {sessions: [], currentPage: 0, next: null, searching: false, count: 0}

    highlight: null

    LIMITS: {my: 20, open: 20, upcoming: 20}

    TYPE_MY: 'my'
    TYPE_OPEN: 'open'
    TYPE_UPCOMING: 'upcoming'

    # if the Find Session screen isn't active, don't 'watch' automatically
    watchingState: false

    init: ->
      # Register with the app store to get @app
      this.listenTo(context.AppStore, this.onAppInit)

    onAppInit: (@app) ->
      return

    defaultQuery: (extra, type) ->
      query =
        limit: @LIMITS[type],
        offset: this[type].currentPage * @LIMITS[type]

      $.extend(query, extra)

    updateSessionState:(session, type) ->
      state = this[type]

      # so callers can realize this is a pinpointed session update
      session.highlight = {new: false, updated: false}
      @highlight = session


      foundIndex = -1

      console.log("STATE", state)
      if state.sessions.length > 0
        for x in [0..state.sessions.length - 1]
          if state.sessions[x].id == session.id
            foundIndex = x
            break

      # session did not exist already. Add it to front of list because that's where interesting stuff should be?
      if foundIndex == -1
        session.highlight.new = true
        console.log("SessionStore.updateSession: adding a new one")
        state.sessions.unshift(session)
      else
        session.highlight.updated = true
        console.log("SessionStore.updateSession: updating existing")
        state.sessions[x] = session


    updateSession: (sessionId) ->
      if !@watchingState
        return

      rest.getSessionHistory(sessionId)
      .done((response) =>
        determined_type = null
        if response.active_music_session
          if response.can_join || context.FriendStore.isFriend(response.user_id)
            determined_type = @TYPE_MY
          else
            determined_type = @TYPE_OPEN
        else
          determined_type = @TYPE_UPCOMING

        @updateSessionState(response, determined_type)
        @issueChange(determined_type)
      )
      .fail((jqXHR) =>
        @app.notifyServerError jqXHR, 'SessionsStore: Unable to fetch session information'
      )

    resetSessions:() ->
      @my.sessions = []
      @my.currentPage = 0
      @my.end = false
      @open.sessions = []
      @open.currentPage = 0
      @open.end = false
      @upcoming.sessions = []
      @upcoming.currentPage = 0
      @upcoming.end = false
      @issueChange(@TYPE_MY)
      @issueChange(@TYPE_OPEN)
      @issueChange(@TYPE_UPCOMING)

    clearSessions: (type, query) ->
      this[type].sessions = []
      this[type].currentPage = 0
      this[type].end = false
      @updateSessions(type, query)

    handleSessionResponse: (type, response) ->
      state = this[type]
      state.sessions = state.sessions.concat(response.sessions)
      state.searching = false
      state.currentPage = state.currentPage + 1
      state.first_search = false
      state.error = null
      state.end = response.sessions.length < @LIMITS[type]
      @issueChange(type)

    handleSessionError: (type, response) ->
      #@app.notifyServerError jqXHR, 'Search Unavailable'
      state = this[type]
      state.searching = false
      state.error = response
      @issueChange(type)

    updateSessions: (type, query) ->

      query = @defaultQuery(query, type)

      this[type].searching = true
      @issueChange(type)

      if type == 'my'
        rest.findFriendSessions(query)
        .done((response) =>
          @handleSessionResponse(type, response)
        )
        .fail((jqXHR) =>
          @handleSessionError(type, jqXHR)
        )

      else if type == 'open'
        rest.findPublicSessions(query)
        .done((response) =>
          @handleSessionResponse(type, response)
        )
        .fail((jqXHR) =>
          @handleSessionError(type, jqXHR)
        )
      else if type == 'upcoming'
        rest.findInactiveSessions(query)
        .done((response) =>
          @handleSessionResponse(type, response)
        )
        .fail((jqXHR) =>
          @handleSessionError(type, jqXHR)
        )

    watching:(watching) ->
      @watchingState = watching

    issueChange: (type) ->
      sessions = this[type]
      @trigger({type: type, sessions: sessions.sessions, highlight: @highlight, searching: sessions.searching, currentPage: sessions.currentPage, end: sessions.end})
      @highlight = null

  }
)