class TopicsGetReadings < ActiveRecord::Migration
  def self.up
    add_column :topics, :reading_count, :integer
    say_with_time "Simulating topic reads by scanning comment postings..." do
      Comment.find(:all).each do |c| 
        Comment.connection.execute("INSERT INTO readings (`participant_id`, `readable_type`, `created_at`, `readable_id`) VALUES(%i, 'Topic', '%s', %i)" % [c.created_by, c.created_at, c.topic_id])
      end
    end
    say_with_time "Simulating topic reads by scanning comment reads..." do
      Comment.find(:all, :include => 'readings').each do |c| 
        value_sets = c.readings.collect do |r|
          "(#{r.participant_id}, 'Topic', '#{r.created_at}', #{c.topic_id})"
        end.join(', ') 
        Comment.connection.execute "INSERT INTO readings (`participant_id`, `readable_type`, `created_at`, `readable_id`)" +
          " VALUES #{value_sets}" unless value_sets.empty?
        end
    end
    say_with_time "updating topics.reading_count..." do
      Topic.find(:all).each do |t|
        t.update_attribute(:reading_count, t.readings.count)
      end
    end
  end

  def self.down
    remove_column :topics, :reading_count
    Reading.delete_all("readable_type = 'Topic'")
  end
end
