# encoding: utf-8
require 'digest/sha2'
class Zamestnanci < ActiveRecord::Base
  set_primary_key :ID_Zam
  set_table_name :zamestnanci
  
  has_and_belongs_to_many :cinnosti, :join_table => 'cinnosti_zam', :foreign_key => 'ID_Zam', :association_foreign_key => 'ID_Cinnost'
  has_many :evidencia_zmluv, :foreign_key => 'ID_Zam'
  
  validates :Meno, :Priezvisko, :Ulica, :Mesto, :Stat, :Telefon, :Email, :Cislo_Bank_Uctu, :Login_IS_Ucet, :Heslo_IS_Ucet, :presence => true
  validates :Fotka, :format => {
    :with => %r{\.(gif|jpg|png)$}i,
    :message => 'Je mozne vlozit adresu URL pre obrazky typu .gif/.jpg/.png'
  }  
  validates_length_of :Meno, :Cislo_Bank_Uctu, :maximum => 15
  validates_length_of :Priezvisko, :maximum => 25
  validates_length_of :Titul, :Fotka, :maximum => 20
  validates_length_of :Rodne_Cislo, :in => 9..11, :message => 'Zle zadané rodné číslo!'
  validates_length_of :Ulica, :Email, :maximum => 50
  validates_length_of :Mesto, :maximum => 30
  validates_length_of :PSC, :maximum => 5
  validates_length_of :Telefon, :in => 13..14, :too_short => 'Prosím vložte aj s predvoľbou +421/+420/...'
  validates_length_of :Login_IS_Ucet, :within => 3..20, :too_short => 'Príliš krátky login!', :too_long => 'Príliš dlhý login!', :uniqueness => true
    
  validates_uniqueness_of :Login_IS_Ucet, :scope => :ID_Zam
  validates :password, :confirmation => true
  validates_length_of :password, :within => 5..20, :too_short => 'Príliš krátke heslo!', :too_long => 'Príliš dlhé heslo!', :confirmation => true

  attr_accessor :password_potvrdenie
  attr_reader :password

  validate :heslo_musi_byt_obsiahnute

    def Zamestnanci.overenie_Zamestnanci(login_IS_Ucet, password) #nefunguje s velkym L
#      logger.info "Parametry: #{login_IS_Ucet} a #{password}"
      if zamestnanci = Zamestnanci.find_by_Login_IS_Ucet(login_IS_Ucet)
#        logger.info "Uzivatel: #{zamestnanci}"
#        logger.info "encrypted: #{encrypt_password(password, zamestnanci.Sol_Heslo)}"
        if zamestnanci.Heslo_IS_Ucet == encrypt_password(password, zamestnanci.Sol_Heslo)
          return zamestnanci
        end
      end
    end

    def Zamestnanci.encrypt_password(password, sol_Heslo)
      Digest::SHA2.hexdigest(password + "nieco" + sol_Heslo)
    end

    def password=(password) #vitualny atribut
      @password = password

      if password.present?
        vygeneruj_Sol_Heslo
        self.Heslo_IS_Ucet = Zamestnanci.encrypt_password(password, self.Sol_Heslo)
      end
    end


    private

    def heslo_musi_byt_obsiahnute
        errors.add(:password, 'Chyba heslo!') unless self.Heslo_IS_Ucet.present?
      end  


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


    
end