# Defines common finders for readables
module ReadingFinderExtension
  # Find the recort that is the most read.
  # 
  # Can be scopped with Klass.with_scope. If you wish to scope Reading, see find_most_recently_read
  #
  # Readings are not scopped. This means that recent reads of old recorts are missed in favour 
  # of focusing on recently created records.
  # It is the difference between finding the record from the last N hours that is the most read
  # vs. finding the comment (from anytime) that is the most read in the last N hours.
  #
  # Does not use Reading.find_most_read_id because that doesn't account for Comment.with_scope
  def find_most_read
    find(:first, 
      :select => "#{table_name}.*, count(*) as 'fresh_reading_count'",
      :joins  => "LEFT JOIN readings ON #{table_name}.id = #{Reading.table_name}.readable_id AND #{Reading.table_name}.readable_type = '#{self.to_s}'",
      :group  => "#{table_name}.id",
      :order  => 'fresh_reading_count DESC'
    )
  end
  
  # Find the records (from anytime) that is the most read in the last N hours. 
  #
  # Uses Reading.find_most_read_id and therefore also uses with_exclusive_scope.
  #
  # Use this method if you wish to scope Reading.
  def find_most_recently_read
    most_read_id = Reading.find_most_read_id(self)
    if most_read_id
      with_exclusive_scope { find(most_read_id) }
    end
  end
  
end