class Admin < ActiveRecord::Base
  
  #attr_accessible :login, :email, :firstname, :name, :password, :password_confirmation, :avatar, :moderator, :as => :admin
  
  has_secure_password
 
  attr_accessor :login, :generate_mdp
 
  validates :password, :presence => true,
                         :confirmation => true,
                         :length => {:within => 6..40},
                         :on => :create
                         
  validates :password,
                         :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) }

  before_validation do
    if self.generate_mdp == "1" and (self.password.to_s == "")
      self.password = "123456"
    end
  end
  
  def mdp_needed?
    if generate_mdp == "1"
      true
    else
      false
      
    end
  end

  def generate_mdp_now
    ps = SecureRandom.hex(4)
    self.password = ps
    self.password_confirmation = ps
    
    if !self.email?
      errors.add(:email, "Doit être présent") 
      
    end
    
    
    if self.save
      GeneralMailer.send_qi_mail("fr", "generation_mdp", self.email, {"mdp" => ps}).deliver
    else
      fgfdggdf = dfgdgf
    end
    
    
  end

  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 
  
  
  SPECIAL_USER_ID = [12]
end
