$ = jQuery
context = window
logger = context.JK.logger
rest = context.JK.Rest()
EVENTS = context.JK.EVENTS
@teacherActions = window.JK.Actions.Teacher

@TeacherStore = Reflux.createStore({
  listenables: @teacherActions
  teacher: null

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

  onAppInit: (app) ->
    @app = app

  defaultTeacher: ->
    {
      experiences_teaching: []
      experiences_education: []
      experiences_award: []
    }

  defaults: (teacher) ->

    if teacher.languages.length == 0
      teacher.languages.push('EN')

  onLoadTeacher: (options) ->
    logger.debug("onLoadTeacher", options)
    if !options?
      throw new Error('@teacher must be specified')

    rest.getTeacher(options)
        .done((savedTeacher) =>
          logger.debug("LOADING TEACHER",savedTeacher)

          @defaults(savedTeacher)

          this.trigger({teacher: savedTeacher}))
        .fail((jqXHR, textStatus, errorMessage) =>
          logger.debug("FAILED",jqXHR, textStatus, errorMessage)
          if (jqXHR.status==404)
            this.trigger({teacher: this.defaultTeacher()})
          else
            context.JK.app.ajaxError(jqXHR, textStatus, errorMessage)
        )

  onSaveTeacher: (teacher, instructions) ->
    logger.debug("onSaveTeacher", teacher, instructions)
    rest.updateTeacher(teacher)
        .done((savedTeacher) =>
          logger.debug("SAVED TEACHER",savedTeacher)
          this.trigger({teacher: savedTeacher})
          if ProfileStore.solo
            ProfileActions.doneTeacherEdit()
          else
            if instructions.navTo?
              logger.debug("NAVIGATING TO",instructions.navTo)
              window.location = instructions.navTo
        ).fail((jqXHR, textStatus, errorMessage) =>
          logger.debug("FAILED",jqXHR, textStatus, errorMessage)
          #errors = JSON.parse(jqXHR.responseText)

          if (jqXHR.status==422)
            logger.debug("FAILED422",jqXHR.responseJSON.errors)
            this.trigger({errors: jqXHR.responseJSON.errors})
            if instructions?.instructions?.direction == 'back'
              if instructions.navTo?
                logger.debug("NAVIGATING TO",instructions.navTo)
                window.location = instructions.navTo
          else
            context.JK.app.ajaxError(textStatus)
        )
  }
)