class Student < ActiveRecord::Base
  has_many :igrades, :dependent => :destroy
  def validate
     # THIS WILL ENFORCE THAT BOTH First_Name and Last_Name WILL BE ENTERED
     errors.add_on_empty %w( name user email)  
  end
  #FOR EMAIL WE CHECK THAT IT IS ALPHANUMERIC, HAS @ AND A PERIOD IN DOMAIN
  validates_format_of :email, 
  :with => /^((\s*)|([a-zA-Z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]{1,}))$/, 
  :message =>" should be: text@text.text"
  validates_numericality_of :groupnum, :allow_nil => true
  validates_uniqueness_of :user
  def before_destroy()
    # IF THE LAST STUDENT IN A GROUP IS REMOVED, SO WILL ALL GROUP'S GRADES
    # (SAME LOGIC AS INDIVIDUAL GRADES FOR ONE STUDENT)
    group=self.groupnum
    if group > 0
      cnt=Student.count(:conditions => "groupnum = #{group}")
      if cnt == 1
        # THIS IS THE LAST STUDENT IN THE GROUP WHO IS BEING REMOVED
        Ggrade.delete_all(:groupnum => "#{group}")
      end
    end    
  end
  
  # IF A STUDENT IS IN A GROUP THAT HAS GRADED ASSIGNMENT, THE STUDENT
  # CAN NO LONGER SWITCH GROUPS, ALSO IF THE STUDENT TRIES TO SWITCH 
  # INTO A GROUP THAT HAS GRADED ASSIGNMENT(S), HE/SHE IS NOT ALLOWED
=begin   
  def before_update()
      @rec_id = read_attribute(:id)
      group=Student.find(:all, :select => "students.groupnum", 
      :conditions => "id = #{@rec_id}").map { |x| x.groupnum }
      if Ggrade.exists?(:groupnum => "#{group}") || 
         Ggrade.exists?(:groupnum => "#{self.groupnum}")
         errors.add_to_base(
         "Either your group has graded assignment(s), or the one you switch into does")
        false
      end  
  end   
=end     
end
