class Uzivatel < ActiveRecord::Base
  
set_table_name :uzivatel

  belongs_to :Zamestnanci, :foreign_key => 'ID_Uzivatel'

  validates :Login_Uzivatel, :presence => true, :uniqueness => true
  validates :password, :confirmation => true

  require 'digest/sha2'
    
  attr_accessor :password_potvrdenie
  attr_reader :password
  
  validate :heslo_musi_byt_obsiahnute
  
  def overenie_Zamestnanci(login_Uzivatel, password)
    if uzivatel = find_by_name(Login_Uzivatel)
      if uzivatel.Hash_Heslo == encrypt_password(password, uzivatel.Sol_Heslo)
        uzivatel
      end
    end
  end
  
  def Zamestnanci.encrypt_password(password, sol_Heslo)
    Digest::SHA2.hexidigest(pasaword + "nieco" + Sol_Heslo)
  end
  
  def password=(password) #vitualny atribut
    @password = password
    
    if password.present?
      vygeneruj.Sol_Heslo
      self.Hash_Heslo = self.class.encrypt_password(password, Sol_Heslo)
    end
  end
  
  
  private
  
  def heslo_musi_byt_obsiahnute
      errors.add(:password, 'Chyba heslo!') unless Hash_Heslo.present?
    end  

  
  def vygeneruj_Sol_Heslo
      self.Sol_Heslo = self.object_id.to_s + rand.to_s
    end
    
end

