# Schema as of Fri Jun 29 21:58:21 EDT 2007 (schema version 45)
#
#  id                  :integer(11)   not null
#  type                :string(255)   
#  value               :string(255)   
#

# ancestor to WhitelistFilterItem and MaskFilterItem.
class RegistrationFilterItem < ActiveRecord::Base
  belongs_to :topic
  has_many   :access_passes, :dependent => :destroy
  has_many   :users, :through => :access_passes
  
  after_save :generate_new_access_passes!
  
  # Generate new AccessPasses based on this filter item. Calls
  # matching_users, which must be defined in descendents.
  def generate_new_access_passes!
    access_passes.destroy_all
    matching_users.each do |user| 
      access_passes.create(:topic => topic, :user => user)
    end
  end
  
  # This method must be defined in descendents.
  def matching_users
    raise NotImplementedError
  end
  
  class << self
    # Generate new AccessPasses for a specific user.
    def generate_new_access_passes_for_user!(user)
      user.access_passes.destroy_all
      find_for_user(user).each do |filter_item|
        filter_item.access_passes.create(:topic => filter_item.topic, :user => user)
      end
    end
    
    def find_for_user(user)
      [WhitelistFilterItem, MaskFilterItem].collect{|klass| klass.find_for_user(user)}.flatten
    end
  end
end
