class StudentUser < ActiveRecord::Base
  #attr_accessible :bio, :email, :firstname, :name, :password, :password_confirmation, :avatar, :moderator
  
  has_secure_password
  validates_presence_of :password, :on => :create
  validates :email, :presence => true, :uniqueness => true, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  validates :name, :presence => true
  validates :firstname, :presence => true
  
  mount_uploader :avatar, AvatarUploader
  
  has_many :messages, :class_name => "StudentMessage"
  has_many :topics, :class_name => "StudentTopic"
  
  has_many :images, :class_name => "StudentUserImage", :order => "created_at DESC"
  
  
  has_many :student_user_groups
  has_many :student_group, :through => :student_user_groups
  has_many :topics, :through => :student_group
  belongs_to :sheet
  
  before_create { generate_token(:auth_token) }
  
  before_validation do
    
    if self.lock_changed? and self.lock
      self.locked_at = Time.now
    end
    
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while StudentUser.exists?(column => self[column])
  end
  
  
end
