class ApiJoinRequestsController < ApiController

  # have to be signed in currently to see this screen
  before_filter :api_signed_in_user

  respond_to :json

  def index
    @join_requests = JoinRequest.index(current_user)
  end
  
  def show
    @join_request = JoinRequest.show(params[:id], current_user)
  end

  def create
    music_session = MusicSession.find(params[:music_session])
    text = params[:text]
    sender = current_user
    
    @join_request = JoinRequest.new
    @join_request.music_session = music_session
    @join_request.user = sender
    @join_request.text = text
    
    @join_request.save

    if @join_request.errors.any?
      response.status = :unprocessable_entity
      respond_with @join_request
    else
      # send notification
      Notification.send_join_request(music_session, @join_request, text)
      respond_with @join_request, :responder => ApiResponder, :location => api_join_request_detail_url(@join_request)
    end
  end

  def update
    @join_request = JoinRequest.find(params[:id])

    if params[:approved]
      # generate invitation if join request is approved
      invitation = Invitation.new
      invitation.sender = current_user
      invitation.receiver = @join_request.user
      invitation.music_session = @join_request.music_session
      invitation.join_request = @join_request
      invitation.save

      Notification.send_join_request_approved(@join_request.music_session, @join_request)
    else
      Notification.send_join_request_rejected(@join_request.music_session, @join_request)
    end
  end

  def delete
    @join_request = JoinRequest.show(params[:id], current_user)
    @join_request.delete

    respond_with @join_request, responder => ApiResponder
  end

end
