class User < ActiveRecord::Base
  include PublicActivity::Common

  belongs_to :person

  rolify
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  # removed :registerable since logins are controlled by admin and not self serve
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :lockable, :timeoutable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :role_ids, :as => :admin
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :active, :person_id

  attr_accessor :include_inactive

  attr_accessor :login
  attr_accessible :login

  validates :email, :presence => true
  validates :name, :presence => true
  validates :username, :presence => true
  validates_uniqueness_of :username

  before_create :setup_default_role

  scope :active, where(:active => 1) 

  # override so we can authenticate by login instead of email
  def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where("active = 1").where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).where("active = 1").first
    end
  end

  private

  def setup_default_role
    if self.role_ids.blank?
      self.add_role :teacher
    end
  end
end
