#encoding: utf-8

class User < ActiveRecord::Base
  belongs_to :team

require 'digest/md5'

  attr_protected :id, :salt

  attr_accessor :password, :password_confirmation
  
  validates_length_of :loginname, :within => 3..40
  validates_uniqueness_of :loginname
  validates_presence_of :loginname, :team_id
  #proc is used as this point because the method/data_field hashed_password is out of scope for the validation methods
  validates_presence_of :password, :if => Proc.new { |u| u.hashed_password.nil?  }
  validates_length_of :password, :within => 5..40, :unless => Proc.new { |u| u.password.nil?  }
  validates_presence_of :password_confirmation, :unless => Proc.new { |u| u.password.nil?  }
  validates_confirmation_of :password, :unless => Proc.new { |u| u.password.nil?  }

  def self.authenticate(loginname, pass)
    user = find(:first, :conditions=>["loginname = ?", loginname])
    return nil if user.nil?
    return user.id if User.encrypt(pass, user.salt)==user.hashed_password rescue nil
    nil
  end
  
  def has_perm?(perm_id)
    return self.team.permissions.exists?(perm_id)
  end

  def is_admin?
    return self.admin_level >= 20
  end

  def is_team_admin?
    return self.admin_level >= 10
  end

  def password=(pass)
    @password=pass
    self.salt = User.random_string(10) unless pass.nil?
    self.hashed_password = User.encrypt(@password, self.salt) unless pass.nil?
  end

  protected

  def self.encrypt(pass, salt)
    Digest::MD5.hexdigest(pass+salt)
  end

  def self.random_string(len)
    #generat a random password consisting of strings and digits
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
  end


end
