class Admin < ActiveRecord::Base
  
  #attr_accessible :login, :email, :firstname, :name, :password, :password_confirmation, :avatar, :moderator, :as => :admin
  
  has_secure_password
 
  attr_accessor :login
 
  validates :password, :presence => true,
                         :confirmation => true,
                         :length => {:within => 6..40},
                         :on => :create
                         
  validates :password, :confirmation => true,
                         :length => {:within => 6..40},
                         :allow_blank => true,
                         :on => :update
 validates :password_confirmation, :presence => true,
    :unless => Proc.new { |a| a.password.blank? }
 
 
  validates :email, :presence => true, :uniqueness => true
  validates :username, :presence => true, :uniqueness => true
  
#  mount_uploader :avatar, AvatarUploader

  before_create { generate_token(:remember_token) }

  def send_password_reset
    generate_token(:reset_password_token)
    self.reset_password_sent_at = Time.now
    save!
    AdminMailer.password_reset(self).deliver
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while Admin.exists?(column => self[column])
  end
  
  def self.find_by_login(login)
    
    Admin.where("username = ? OR email = ?", login,login).first
    
  end 
end
