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

TeacherSearchResultsActions = @TeacherSearchResultsActions

@TeacherSearchResultsStore = Reflux.createStore(
  {
    listenables: TeacherSearchResultsActions
    results: []
    page: 1
    limit: 20
    searching: false

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

    onAppInit: (app) ->
      @app = app

    onReset: () ->
      @results = []
      @page = 1
      @searching = true
      @changed()

      query = @createQuery()

      rest.searchTeachers(query)
      .done((response) =>
        @next = response.next
        @searching = false
        @results.push.apply(@results, response.entries)
        @changed()
      )
      .fail((jqXHR, textStatus, errorMessage) =>
        @searching = false
        @changed()
        @app.ajaxError(jqXHR, textStatus, errorMessage)
      )

    nextPage: () ->
      @page += 1

      query = @createQuery()

      @searching = true
      rest.searchTeachers(query)
      .done((response) =>
        @next = response.next
        @results.push.apply(@results, response.entries)
        @searching = false
        @changed()
      )
      .fail((jqXHR, textStatus, errorMessage) =>
        @searching = false
        @app.ajaxError(jqXHR, textStatus, errorMessage)
        @changed()
      )

    getState: () ->
      ({results: @results, next: @next, currentPage: @page, searching: @searching})

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

    createQuery: () ->

      searchOptions = context.TeacherSearchStore.getState()

      query = {}
      query.page = @page
      query.per_page = @limit
      query.instruments = searchOptions.instruments
      query.subjects = searchOptions.subjects
      query.genres = searchOptions.genres
      query.languages = searchOptions.languages
      query.teaches_beginner = searchOptions.teaches_beginner
      query.teaches_intermediate = searchOptions.teaches_intermediate
      query.teaches_advanced = searchOptions.teaches_advanced
      query.student_age = searchOptions['ages-taught']
      query.years_teaching = searchOptions['years-teaching']
      query.country = searchOptions.location?.country
      query.region = searchOptions.location?.region
      query.onlyMySchool = searchOptions.onlyMySchool
      query

      query
  }
)