# 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)   
#

class MaskFilterItem < RegistrationFilterItem
  
  def value=(glob_string)
    write_attribute(:value, glob2sql(glob_string))
  end
  
  def value
    sql2glob(read_attribute(:value))
  end  
  
  # Return an array of matching RegisteredUsers
  def matching_users
    RegisteredUser::__rails_cannot_find_descendants_fix
    RegisteredUser.find(:all, :conditions => ['email LIKE ?', read_attribute(:value)])
  end
  
  # Rudementary glob-to-SQL-like converter
  # 
  # - escape current content
  # - translate * to %
  def glob2sql(glob_string)
    glob_string.gsub(/%|_/,'\&').gsub('*', '%')
  end

  def sql2glob(sql_string)
    sql_string.gsub(/(%|_)/,'\&').gsub('%', '*')
  end

  class << self
    def match?(email)
      find(:first, :conditions => ["? LIKE #{table_name}.value", email])
    end
    
    def find_for_user(user)
      find(:all, :conditions => ["? LIKE #{table_name}.value", user.email])
    end
  end
end
