class UpdatePrincipalActivityTime < ActiveRecord::Migration
  def up
    count = PrincipalActivity.all.count / 30 + 2
    transaction do
      for i in 1 ... count do i
        PrincipalActivity.page(i).per(30).each do |activity|
          if activity.principal_act
            if activity.principal_act.respond_to?("created_on")
              activity.created_at = activity.principal_act.created_on
              activity.updated_at = activity.principal_act.created_on
            elsif activity.principal_act.respond_to?("created_at")
              activity.created_at = activity.principal_act.created_at
              activity.updated_at = activity.principal_act.created_at
            end
            activity.save

            user_activity = UserActivity.where("act_type = '#{activity.principal_act_type.to_s}' and act_id = '#{activity.principal_act_id}'").first
            user_activity.created_at = activity.created_at
            user_activity.updated_at = activity.created_at
            if user_activity.act_type == 'JournalsForMessage'
              if user_activity.act
                unless user_activity.act.m_parent_id.nil?
                  parent_act = UserActivity.where("act_id = #{user_activity.act.m_parent_id} and act_type='JournalsForMessage' and container_type='Principal'").first
                  if parent_act
                    parent_act.created_at = user_activity.act.parent.children.maximum("created_on")
                    parent_act.save
                    user_activity.destroy
                  end
                end
              else
                user_activity.destroy
              end
            end
            user_activity.save
          end
        end
      end
    end
  end

  def down
  end
end
