# Schema as of Fri Jun 29 21:58:21 EDT 2007 (schema version 45)
#
#  id                  :integer(11)   not null
#  name                :string(255)   
#  type                :string(255)   
#  email               :string(100)   
#  crypted_password    :string(40)    
#  salt                :string(40)    
#  created_at          :datetime      
#  bio                 :text          
#  picture             :string(255)   
#  user_number         :string(255)   
#  year_of_birth       :integer(11)   
#  gender              :integer(11)   default(0)
#  postal_code         :string(255)   
#  login_key           :string(255)   
#  verified            :boolean(1)    
#  login_key_expires_at:datetime      
#  avg_rating          :float         
#  suspended           :boolean(1)    
#  receive_messages_fro:boolean(1)    default(true)
#

class Participant < RegisteredUser
  has_many :readings, :foreign_key => :participant_id, :dependent => :delete_all
  #validates_presence_of :user_number # if recording_user_numbers?
  
  # TODO in the future, we can validate the user_numbers against a whitelist
  
  #validates_uniqueness_of :user_number  
  
  validates_uniqueness_of :name, :message => '^Username has already been taken'
  validates_length_of :name, 
    :within => 3..50, 
    :too_long => "^Username is too long (max is %d characters)", 
    :too_short => "^Username is too short (min is %d characters)"
  validates_inclusion_of :year_of_birth, :in=>1900..2005, :on => :create, :message=>"is not valid"
  validates_inclusion_of :gender, :in=>[1,2], :message=>"is not valid"
  validate :format_of_postal_or_zip_code
  
  # postal code validation pattern
  POSTAL_CODE_START_REGEXP = /^[A-Z]\d[A-Z]$/
  ZIP_CODE_START_REGEXP    = /^\d{3}$/
  
  def before_validation
    clean_up_postal_code
  end
  
  # test postal code against canadian pattern
  def format_of_postal_or_zip_code
    errors.add('postal_code') unless postal_code && (postal_code.match(POSTAL_CODE_START_REGEXP) || postal_code.match(ZIP_CODE_START_REGEXP))      
  end
  
  # tidies up input of postal code
  # should only be called durring before_validation
  def clean_up_postal_code
    unless self.postal_code.blank?
      self.postal_code.strip!
      self.postal_code.upcase! 
      self.postal_code = postal_code[0..2] # in case of old data with 6 digit codes
    end
  end
  
  def handle
    name
  end
  
  def handle=(new_handle)
    name=(new_handle)
  end
  
  # Take reading and rating activity from a guest account and move it to a new Participant account
  def take_activity_from_guest_account!(previously_held_guest_account)
    Reading.move_to_new_user(previously_held_guest_account, self)
    AbstractRating.move_to_new_user(previously_held_guest_account, self) # moves all ratings
    super
  end
  
  def year_of_birth=(yob)
    yob = yob.to_i
    yob = yob + 1900 if (yob < 99 && yob > 0)
    self[:year_of_birth]=yob
  end
  
end
