module JamRuby
  class FriendRequest < ActiveRecord::Base

    self.primary_key = 'id'

    STATUS = %w(accept block spam ignore)

    belongs_to :user, :class_name => "JamRuby::User"
    belongs_to :friend, :class_name => "JamRuby::User"

    validates :user_id, :presence => true
    validates :friend_id, :presence => true
    #validates :status, :inclusion => {:in => STATUS}
    validates :message, no_profanity: true

    def to_s
      return "#{self.id} => #{self.user.to_s}:#{self.friend.to_s}"
    end

    def self.save(id, user_id, friend_id, status, message)
      # new friend request
      if id.nil?
        friend_request = FriendRequest.new()
        friend_request = validate_friend_request(friend_request, user_id, friend_id)
        friend_request.user_id = user_id
        friend_request.friend_id = friend_id
        friend_request.message = message
        friend_request.save

        # send notification
        Notification.send_friend_request(friend_request.id, user_id, friend_id)
        
      else
        ActiveRecord::Base.transaction do
          friend_request = FriendRequest.find(id)
          friend_request.status = status
          friend_request.updated_at = Time.now.getutc
          friend_request.save

          # create both records for this friendship
          if friend_request.status == "accept"
            Friendship.save(friend_request.user_id, friend_request.friend_id)

            # send notification
            Notification.send_friend_request_accepted(friend_request.user_id, friend_request.friend_id)
          end
        end
      end

      return friend_request
    end

    private
      def self.validate_friend_request(friend_request, user_id, friend_id)
        friend_requests = FriendRequest.where("user_id='#{user_id}' AND friend_id='#{friend_id}'")
        
        # check if there are any friend requests for this source/target user combo, and if
        # any have been marked as spam or blocked, set the status of this friend request
        # to match so it doesn't show up in the queue
        unless friend_requests.nil? || friend_requests.size == 0
          if friend_requests.exists?(:status => "spam")
            friend_request.status = "spam"

          elsif friend_requests.exists?(:status => "block")
            friend_request.status = "block"
          end
        end
        return friend_request
      end
  end
end
