module JamRuby
  class Invitation < ActiveRecord::Base

    FRIENDSHIP_REQUIRED_VALIDATION_ERROR = "You can only invite friends"
    MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION = "You must be a member of the music session to send invitations on behalf of it"
    JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION = "You can only associate a join request with an invitation if that join request comes from the invited user and if it's for the same music session"

    self.primary_key = 'id'
    belongs_to :sender, :inverse_of => :sent_invitations, :class_name => "JamRuby::User", :foreign_key => "sender_id"
    belongs_to :receiver, :inverse_of => :received_invitations, :class_name => "JamRuby::User", :foreign_key => "receiver_id"
    belongs_to :music_session, :inverse_of => :invitations, :class_name => "JamRuby::MusicSession"
    belongs_to :join_request, :inverse_of => :invitations, :class_name => "JamRuby::JoinRequest"

    validates :sender, :presence => true
    validates :receiver, :presence => true
    validates :music_session, :presence => true
    
    validate :require_sender_in_music_session, :require_are_friends_or_requested_to_join

    private

    def require_sender_in_music_session
      unless music_session.users.exists? sender
         errors.add(:music_session, MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION)
      end
    end

    def require_are_friends_or_requested_to_join
      if !join_request.nil? && (join_request.user != receiver || join_request.music_session != music_session)
        errors.add(:join_request, JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION )
      elsif join_request.nil?
        # we only check for friendship requirement if this was not in response to a join_request
        unless receiver.friends.exists? sender
          errors.add(:receiver, FRIENDSHIP_REQUIRED_VALIDATION_ERROR)
        end
      end
    end
  end
end
