module JamRuby
  class Friendship < ActiveRecord::Base

    attr_accessible :user_id, :friend_id

    self.primary_key = 'id'

    belongs_to :user, :class_name => "JamRuby::User", :foreign_key => "user_id", :inverse_of => :inverse_friendships
    belongs_to :friend, :class_name => "JamRuby::User", :foreign_key => "friend_id", :inverse_of => :friendships

    after_save :track_user_progression

    def self.save(user_id, friend_id)
      friendship = Friendship.where("user_id='#{user_id}' AND friend_id='#{friend_id}'")

      if friendship.nil? || friendship.size == 0
        Friendship.create(:user_id => user_id, :friend_id => friend_id)
        Friendship.create(:user_id => friend_id, :friend_id => user_id)
      end
    end


    # not like .save() in that it does not check for an existing friendship.  The caller is responsible
    # for checking for errors on the models
    def self.save_using_models(user, friend)
      this = Friendship.new
      this.user = user
      this.friend = friend

      that = Friendship.new
      that.user = friend
      that.friend = user

      this.save
      that.save
      return [this, that]
    end

    def self.search(query, user_id, options = { :limit => 10 })
      # only issue search if at least 2 characters are specified
      if query.nil? || query.length < 2 || user_id.nil?
        return []
      end

      # create 'anded' statement
      query = Search.create_tsquery(query)

      if query.nil? || query.length == 0
        return []
      end
      
      friends = Friendship.joins(
          %Q{
            INNER JOIN
              users
            ON friendships.friend_id = users.id
            WHERE friendships.user_id = '#{user_id}'
            AND users.name_tsv @@ to_tsquery('jamenglish', '#{query}')
          }
        )        

        friends = friends.limit(options[:limit])
        return friends
    end

    def track_user_progression
      self.user.update_progression_field(:first_friended_at)
    end
  end
end