$ = jQuery
context = window
logger = context.JK.logger

rest = context.JK.Rest()

AttachmentActions = @AttachmentActions


@AttachmentStore = Reflux.createStore(
  {
    listenables: AttachmentActions
    lessonId: null
    uploading: false

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

    onAppInit: (@app) ->
      @ui = new context.JK.UIHelper(@app);

    recordingsSelected: (recordings) ->
      logger.debug("recording selected", recordings)

      if @lessonId
        options = {id: @lessonId}
        options.recordings = recordings
        rest.attachRecordingToLesson(options).done((response) => @attachedRecordingsToLesson(response)).fail((jqXHR) => @attachedRecordingsFail(jqXHR))
      else if @sessionId
        options = {id: @sessionId}
        options.recordings = recordings
        rest.attachRecordingToSession(options).done((response) => @attachedRecordingsToSession(response)).fail((jqXHR) => @attachedRecordingsFail(jqXHR))

    attachedRecordingsToLesson: (response) ->
      context.JK.Banner.showNotice('Recording Attached', 'Your recording has been associated with this lesson, and can be accessed from the Messages window for this lesson.')

    attachedRecordingsToSession: (response) ->
      context.JK.Banner.showNotice('Recording Attached', 'Your recording has been associated with this session.')

    attachedRecordingsFail: (jqXHR) ->
      @app.ajaxError(jqXHR)

    onStartAttachRecording: (lessonId, sessionId = null) ->
      if @uploading
        logger.warn("rejecting startAttachRecording attempt as currently busy")
        return
      @lessonId = lessonId
      @sessionId = sessionId

      @ui.launchRecordingSelectorDialog([], (recordings) =>
        @recordingsSelected(recordings)
      )
      @changed()

    onStartAttachNotation: (lessonId, sessionId = null) ->
      if @uploading
        logger.warn("rejecting onStartAttachNotation attempt as currently busy")
        return
      @lessonId = lessonId
      @sessionId = sessionId


      logger.debug("notation upload started for lesson: " + lessonId)
      @triggerNotation()
      @changed()

    onStartAttachAudio: (lessonId, sessionId = null) ->
      if @uploading
        logger.warn("rejecting onStartAttachAudio attempt as currently busy")
        return
      @lessonId = lessonId
      @sessionId = sessionId

      logger.debug("audio upload started for lesson: " + lessonId)
      @triggerAudio()
      @changed()

    triggerNotation: () ->
      if !@attachNotationBtn?
        @attachNotationBtn = $('input.attachment-notation').eq(0)
      console.log("@attachNotationBtn", @attachNotationBtn)
      @attachNotationBtn.trigger('click')

    triggerAudio: () ->
      if !@attachAudioBtn?
        @attachAudioBtn = $('input.attachment-audio').eq(0)
      console.log("@@attachAudioBtn", @attachAudioBtn)
      @attachAudioBtn.trigger('click')


    onUploadNotations: (notations, doneCallback, failCallback) ->
      logger.debug("beginning upload of notations", notations)
      @uploading = true
      @changed()

      formData = new FormData()
      maxExceeded = false;
      $.each(notations, (i, file) => (
        max = 10 * 1024 * 1024;
        if file.size > max
          maxExceeded = true
          return false

        formData.append('files[]', file)
      ))

      if maxExceeded
        @app.notify({
          title: "Maximum Music Notation Size Exceeded",
          text: "You can only upload files up to 10 megabytes in size."
        })
        failCallback()
        @uploading = false
        @changed()
        return


      if @lessonId
        formData.append('lesson_session_id', @lessonId)
      else if @sessionId
        formData.append('session_id', @sessionId)

      formData.append('attachment_type', 'notation')

      @app.layout.showDialog('music-notation-upload-dialog')

      rest.uploadMusicNotations(formData)
      .done((response) => @doneUploadingNotatations(notations, response, doneCallback, failCallback))
      .fail((jqXHR) => @failUploadingNotations(jqXHR, failCallback))

    doneUploadingNotatations: (notations, response, doneCallback, failCallback) ->
      @uploading = false
      @changed()
      error_files = [];
      $.each(response, (i, music_notation) => (
        if music_notation.errors
          error_files.push(notations[i].name)
      )
      )
      if error_files.length > 0
        failCallback()
        @app.notifyAlert("Failed to upload notations.", error_files.join(', '));
      else
        doneCallback()

    failUploadingNotations: (jqXHR, failCallback) ->
      @uploading = false
      @changed()
      if jqXHR.status == 413
        # the file is too big.   Let the user know.
        # This should happen when they select the file, but a misconfiguration on the server could cause this.
        @app.notify({
          title: "Maximum Music Notation Size Exceeded",
          text: "You can only upload files up to 10 megabytes in size."
        })
      else
        @app.notifyServerError(jqXHR, "Unable to upload music notations");

    onUploadAudios: (notations, doneCallback, failCallback) ->
      logger.debug("beginning upload of audio", notations)
      @uploading = true
      @changed()

      formData = new FormData()
      maxExceeded = false;
      $.each(notations, (i, file) => (
        max = 10 * 1024 * 1024;
        if file.size > max
          maxExceeded = true
          return false

        formData.append('files[]', file)
      ))

      if maxExceeded
        @app.notify({
          title: "Maximum Music Audio Size Exceeded",
          text: "You can only upload files up to 10 megabytes in size."
        })
        failCallback()
        @uploading = false
        @changed()
        return


      if @lessonId
        formData.append('lesson_session_id', @lessonId)
      else if @sessionId
        formData.append('session_id', @sessionId)

      formData.append('attachment_type', 'audio')

      @app.layout.showDialog('music-notation-upload-dialog')

      rest.uploadMusicNotations(formData)
      .done((response) => @doneUploadingAudios(notations, response, doneCallback, failCallback))
      .fail((jqXHR) => @failUploadingAudios(jqXHR, failCallback))

    doneUploadingAudios: (notations, response, doneCallback, failCallback) ->
      @uploading = false
      @changed()
      error_files = [];
      $.each(response, (i, music_notation) => (
        if music_notation.errors
          error_files.push(notations[i].name)
      )
      )
      if error_files.length > 0
        failCallback()
        @app.notifyAlert("Failed to upload audio files.", error_files.join(', '));
      else
        doneCallback()

    failUploadingAudios: (jqXHR, failCallback) ->
      @uploading = false
      @changed()
      if jqXHR.status == 413
        # the file is too big.   Let the user know.
        # This should happen when they select the file, but a misconfiguration on the server could cause this.
        @app.notify({
          title: "Maximum Music Audio Size Exceeded",
          text: "You can only upload files up to 10 megabytes in size."
        })
      else
        @app.notifyServerError(jqXHR, "Unable to upload music audio files");


    changed: () ->
      this.trigger({lessonId: @lessonId, uploading: @uploading})
  }
)