# Schema as of Fri Jun 29 21:58:21 EDT 2007 (schema version 45)
#
#  id                  :integer(11)   not null
#  participant_id      :integer(11)   default(0), not null
#  readable_id         :integer(11)   
#  created_at          :datetime      
#  readable_type       :string(255)   
#

# Represents an instance of a user reading (or at least accessing) a readable 
# object (currently either SupportMaterial or Comment)
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, :readable_type], :if => Proc.new { |reading| reading.readable.is_a?(SupportMaterial) }
  
  class << self
    # Move readings from one user to another. This method is useful for moving Guest readings to a Participant
    # when they authenticate after having browsed around for a bit.
    def move_to_new_user(from_user, to_user)
      update_all("participant_id = #{to_user.id}", ['participant_id = ?', from_user.id])
    end
    
    # Find the ++id++ of the readable that is most read.
    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
     
    include RuportQueryOverArConnection

    def report
      report_table(:all, 
        :order => "#{Reading.table_name}.created_at ASC"
        )
    end
    
    def report_comment_reading(topic_id=nil)
      where = "WHERE comments.topic_id = #{topic_id}" if topic_id
      report_raw("SELECT readings.participant_id as `user_id`, readings.id, readable_id as `comment_id`, readings.created_at FROM readings INNER JOIN comments ON readings.readable_id = comments.id AND readings.readable_type = 'Comment' #{where} ORDER BY readings.created_at ASC")
    end
    
    def report_support_material_reading(topic_id=nil)
      where = "WHERE support_materials.topic_id = #{topic_id}" if topic_id
      report_raw("SELECT readings.participant_id as `user_id`, readings.id, readable_id as `support_material_id`, readings.created_at FROM readings INNER JOIN support_materials ON readings.readable_id = support_materials.id AND readings.readable_type = 'SupportMaterial' #{where} ORDER BY readings.created_at ASC")
    end
    
    def report_topic_reading(topic_id=nil)
      additional_condition = "AND readings.readable_id = #{topic_id}" if topic_id
      report_raw("SELECT participant_id as `user_id`, id, readable_id as `topic_id`, created_at FROM readings WHERE ( readings.readable_type = 'Topic' #{additional_condition}) ORDER BY readings.created_at ASC")
    end
    
  end
end
