# Schema as of Mon Nov 27 15:17:56 EST 2006 (schema version 35)
#
#  id                  :integer(11)   not null
#  participant_id      :integer(11)   default(0), not null
#  readable_id         :integer(11)   
#  created_at          :datetime      
#  readable_type       :string(255)   
#

class Reading < ActiveRecord::Base
  belongs_to :user, :foreign_key => :participant_id
  # counter_cache is a bit broken, see http://dev.rubyonrails.org/ticket/6197
  belongs_to :readable, :polymorphic => true, :counter_cache => :reading_count
  
  validates_uniqueness_of :participant_id, :scope => [:readable_id], :if => Proc.new { |reading| reading.readable.is_a?(SupportMaterial) }
  
  class << self
    def move_to_new_user(from_user, to_user)
      update_all("participant_id = #{to_user.id}", ['participant_id = ?', from_user.id])
    end
  
    def find_most_read_id(readable)
      id_count_array = count(:conditions => ['readable_type = ?', readable.to_s.classify], :group => 'readable_id')
      max_id, read_count = id_count_array.max{|a,b| a[1] <=> b[1]}
      return max_id
    end
  end
end
