class ApiInvitationsController < ApiController

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

  respond_to :json

  def index
    conditions = {}
    sender_id = params[:sender]
    receiver_id = params[:receiver]

    if !sender_id.nil?
      if current_user.id != sender_id
        raise JamPermissionError, "You can only ask for your own sent invitations"
      end
      if session_id = params[:session_id]
        @invitations = Invitation.where(:sender_id => sender_id, :music_session_id => session_id).to_a.uniq { |i| i.receiver_id }
      else
        @invitations = Invitation.where(:sender_id => current_user.id).to_a.uniq { |i| i.receiver_id }
      end
    elsif !receiver_id.nil?
      if current_user.id != receiver_id
        raise JamPermissionError, "You can only ask for your own received invitations"
      end

      @invitations = Invitation.where(:receiver_id => current_user.id).to_a.uniq { |i| i.receiver_id }
    else
      # default to invitations you've received
      @invitations = Invitation.where(:receiver_id => current_user.id).to_a.uniq { |i| i.receiver_id }
    end
  end

  def create
    music_session = MusicSession.find(params[:music_session])
    receiver = User.find(params[:receiver])
    sender = current_user
    join_request = JoinRequest.find(params[:join_request]) unless params[:join_request].nil?

    @invitation = Invitation.new
    @invitation.music_session = music_session
    @invitation.sender = sender
    @invitation.receiver = receiver
    @invitation.join_request = join_request
    @invitation.save

    unless @invitation.errors.any?
      User.save_session_settings(current_user, music_session)

      # send notification
      Notification.send_session_invitation(receiver, current_user, music_session.id)
      respond_with @invitation, :responder => ApiResponder, :location => api_invitation_detail_url(@invitation)

    else
      # we have to do this because api_invitation_detail_url will fail with a bad @invitation
      response.status = :unprocessable_entity
      respond_with @invitation
    end

  end

  def show
    @invitation = Invitation.where(["receiver_id = ? or sender_id = ?", current_user.id, current_user.id]).find(params[:id])
  end
  
  def delete
    @invitation = Invitation.where(["sender_id = ?", current_user.id]).find(params[:id])
    @invitation.delete

    respond_with @invitation, responder => ApiResponder
  end
end
