class ApiRsvpRequestsController < ApiController

  before_filter :api_signed_in_user

  respond_to :json

  def index
    if params[:session_id].blank?
      render :json => {:message => "Session ID is required"}, :status => 400

    else
      music_session = MusicSession.find(params[:session_id])

      # retrieve all requests for this session
      creator = music_session.creator
      if creator && creator.id == current_user.id
        @rsvp_requests = RsvpRequest.index(music_session, nil, params)

      # scope the response to the current user
      else
        @rsvp_requests = RsvpRequest.index(music_session, current_user, params)
      end

      respond_with @rsvp_requests, responder: ApiResponder, :status => 200
    end
  end

  def create
    if params[:session_id].blank?
      render :json => {:message => "Session ID is required."}, :status => 400
    else
      @rsvp = RsvpRequest.create(params, current_user)
      respond_with @rsvp, responder: ApiResponder, :status => 201
    end
  end

  def update
    if params[:id].blank?
      render :json => {:message => "RSVP request ID is required."}, :status => 400
    else
      RsvpRequest.update(params, current_user)
      render :json => {:message => "Changes saved."}, :status => 204
    end
  end

  def show
    @rsvp_request = RsvpRequest.find(params[:id])
    respond_with @rsvp_request, responder: ApiResponder, :status => 200
  end

  def destroy
    @rsvp_request = RsvpRequest.cancel(params, current_user)
    if !@rsvp_request.nil? && @rsvp_request.errors.any?
      render :json => @rsvp_request.errors, :status => 400 and return
    end

    respond_with responder: ApiResponder, :status => 204
  end
end