require 'aws-sdk'

class ApiMusicNotationsController < ApiController
  before_filter :api_signed_in_user

  respond_to :json

  def create
    @music_notations = []

    lesson_session = LessonSession.find_by_id(params[:lesson_session_id])

    if lesson_session
      session = lesson_session.music_session
    else
      session = MusicSession.find(params[:session_id])
    end


    params[:files].each do |file|
      music_notation = MusicNotation.create(session.id, params[:attachment_type], file, current_user)
      @music_notations.push music_notation


      if lesson_session
        if lesson_session.student.id == current_user.id
          me = lesson_session.student
          other = lesson_session.teacher
        else
          me = lesson_session.teacher
          other = lesson_session.student
        end
      else
        me = current_user
      end


      if !music_notation.errors.any?
        # if no error and it's a lesson, then make a chat about it

        if params[:attachment_type] == MusicNotation::TYPE_NOTATION
          purpose = "Notation File"
        else
          purpose = "Audio File"
        end

        if lesson_session
          msg = ChatMessage.create(me, nil, '', ChatMessage::CHANNEL_LESSON, nil, other, lesson_session, purpose, music_notation)
          UserMailer.lesson_attachment(me, other, lesson_session, music_notation)
        else
          if session.active_music_session
            msg = ChatMessage.create(me, session.active_music_session, '', ChatMessage::CHANNEL_SESSION, nil, nil, nil, purpose, music_notation)
          end
        end

      end


    end if params[:files]

    respond_with @music_notations, responder: ApiResponder, :status => 201
  end

  def download
    @music_notation = MusicNotation.find(params[:id])

    unless @music_notation.music_session.can_join?(current_user, true)
      render :text => "Permission denied", status: 403
      return
    end

    if '_blank'==params[:target]
      redirect_to @music_notation.sign_url
    else
      render :json => {url: @music_notation.sign_url}
    end
  end

  def delete
    @music_notation = MusicNotation.find(params[:id])

    unless @music_notation.music_session.can_join?(current_user, true)
      render :text => "Permission denied", status: 403
      return
    end

    @music_notation.destroy

    render :json => {}, status: 204
  end
end
