class ApiInvitedUsersController < ApiController

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

  respond_to :json

  def index
    @invited_users = InvitedUser.index(current_user)
  end

  def show
    if InvitedUser::FB_MEDIUM == params[:id]
      @invited_user = current_user.facebook_invite!
    else
      @invited_user = InvitedUser.find(params[:id])
    end
  end

  def create
    @invited_users = []
    if (emails = params[:emails]).present?
      emails = emails[0...Rails.application.config.max_email_invites_per_request].uniq
      if emails.include?(current_user.email)
        @responseobject = { :errors  => { :email => ["can't be your own address"]}}
        render :json => @responseobject, :status => :unprocessable_entity, layout: nil
        return
      end

      # remove due to spammers
      msg = params[:note].blank? ? nil : params[:note].strip



      @invited_users = emails.collect do |ee|
        iu = InvitedUser.new
        iu.sender = current_user
        iu.email = ee.strip
        iu.autofriend = true
        iu.note = msg
        iu.save

        if iu.receiver
          # automatically create friend request for an invitation to an existing user
          FriendRequest.save(nil,
                             current_user.id,
                             iu.receiver.id,
                             nil,
                             msg)
        end
        iu
      end
    else
      iu = InvitedUser.new
      iu.sender = current_user
      iu.save
      @invited_users = [iu]
    end
    if err = @invited_users.detect {|iu| iu.errors.any? }
      response.status = :unprocessable_entity
      respond_with err
    end
  end

end