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

@SchoolStore = Reflux.createStore(
  {
    school: null,
    teacherInvitations: null
    studentInvitations: null

    listenables: @SchoolActions

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

    onAppInit: (@app) ->

    onLoaded: (response) ->
      @school = response

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

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

      @changed()
      rest.listSchoolInvitations({id:@school.id, as_teacher: true}).done((response) => @onLoadedTeacherInvitations(response)).fail((jqXHR) => @onSchoolInvitationFail(jqXHR))

    onLoadedTeacherInvitations: (response) ->
      @teacherInvitations = response.entries
      @changed()
      rest.listSchoolInvitations({id:@school.id, as_teacher: false}).done((response) => @onLoadedStudentInvitations(response)).fail((jqXHR) => @onSchoolInvitationFail(jqXHR))

    onLoadedStudentInvitations: (response) ->
      @studentInvitations = response.entries
      @changed()

    onAddInvitation: (isTeacher, invitation) ->
      if isTeacher
        @teacherInvitations.push(invitation)
      else
        @studentInvitations.push(invitation)
      @changed()

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

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

      @changed()

    onRefresh: (schoolId) ->
      if !schoolId?
        schoolId = @school?.id
      rest.getSchool({id: schoolId}).done((response) => @onLoaded(response)).fail((jqXHR) => @onSchoolFail(jqXHR))

    onUpdateSchool: (school) ->
      @school = school
      @changed()

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

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

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

    getState:() ->
      {school: @school, studentInvitations: @studentInvitations, teacherInvitations: @teacherInvitations}
  }
)
