module JamRuby
  class FriendRequest < ActiveRecord::Base
    include HtmlSanitize
    html_sanitize strict: [:message]

    self.primary_key = 'id'

    STATUS = %w(accept block spam ignore)

    belongs_to :user, :class_name => "JamRuby::User", :foreign_key => 'user_id'
    belongs_to :friend, :class_name => "JamRuby::User", :foreign_key => 'friend_id'

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

    validate :same_school_protection

    def same_school_protection
      if self.user_id && self.user.nil?
        self.user = User.find(user_id)
      end
      if self.friend_id && self.friend.nil?
        self.friend = User.find(friend_id)
      end

      if self.user && self.friend
        if !self.user.is_platform_instructor && !self.friend.is_platform_instructor
          if self.user.school_id != self.friend.school_id
            errors.add(:friend, ValidationMessages::CAN_ONLY_CHAT_SAME_SCHOOL)
          end
        end
      end
    end

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

    def self.invited_path(invited_user, sender, message)
      friend_request = self.save(nil, sender.id, invited_user.id, nil, message, supress_initial: true)
      self.save(friend_request.id, sender.id, invited_user.id, 'accept', message, supress_initial: true)
    end

    def self.save(id, user_id, friend_id, status, message, supress_initial: false)
      # 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
        if friend_request.save
          # send notification
          Notification.send_friend_request(friend_request.id, user_id, friend_id) unless supress_initial
        end


      else
        ActiveRecord::Base.transaction do
          friend_request = FriendRequest.find(id)
          friend_request.status = status
          friend_request.save

          duplicate_requests = FriendRequest.where("user_id = ? AND friend_id = ?", user_id, friend_id)

          duplicate_requests.each do |req|
            req.status = status
            req.save
          end

          # create both records for this friendship
          if friend_request.status == "accept"
            if 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
      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
