class User
  
  include Mongoid::Document
  include Mongoid::Timestamps

  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :registerable
  
  mount_uploader :avatar, AvatarUploader
  
  field :admin, :type => Boolean, :default => true
  field :active_role
  field :nccu_ldap_uid
  
  # field :cache_dept
  # has_one :cache_dept, :class_name => "I18nVariable", :as => :language_value, :autosave => true, :dependent => :destroy
  field :cache_dept,type: Hash

  has_many :attribute_values, :autosave => true, :dependent => :destroy
  has_many :app_auths,as: :privilege_apps,:inverse_of => :privilege_lists
  has_many :blocked_apps,  :inverse_of => :blocked_users, :class_name => "AppAuth", :dependent => :destroy
  has_many :privilege_apps,  :inverse_of => :privilege_users, :class_name => "AppAuth", :dependent => :destroy
  
  has_many :managing_apps,:class_name => "AppManager", :dependent => :destroy
  
  belongs_to :role
  has_and_belongs_to_many :sub_roles
  accepts_nested_attributes_for :attribute_values, :allow_destroy => true

  def create_dept_cache
    dept_hash = {}

    VALID_LOCALES.each  do |loc|
      locale = loc.to_sym
          # debugger
      # if(self.cache_dept.nil?)
      #   self.build_cache_dept key: "dept_cache_user_#{self.id}"
      # end
      dept_hash[locale] = sub_roles.collect{|sr| sr.i18n_variable[locale]}.join(',')
      # self.cache_dept[locale] = sub_roles.collect{|sr| sr.i18n_variable[locale]}.join(',')
    end
    self.cache_dept = dept_hash
    self.save!
  end

  def self.current
    Thread.current[:user]
  end

  def self.current=(user)
     Thread.current[:user] = user
  end
  
  scope :remote_account, where(:nccu_id.ne => nil)

  def self.current
    Thread.current[:user]
  end
   
  def self.current=(user)
     Thread.current[:user] = user
  end
  
  def avb_apps
    sub_role_ids_ary=self.sub_roles.collect{|t| t.id}
    query1 = AppAuth.any_in({sub_role_ids: sub_role_ids_ary}).excludes(blocked_user_ids: self.id)
    query2 = AppAuth.any_of({all: true},{privilege_user_ids: self.id},{role_ids: self.role.id}).excludes(blocked_user_ids: self.id)
    (query1 + query2).uniq
  end
  
  def name
    info = Class::Info.first(:conditions => {:key => 'profile'})
    if info
      first_name = get_attribute_values.detect {|value| value.key.to_s.eql?('first_name') }[I18n.locale.to_s] rescue nil
      last_name = get_attribute_values.detect {|value| value.key.to_s.eql?('last_name') }[I18n.locale.to_s] rescue nil
      return "#{last_name} #{first_name}"
    else
      return nil
    end
  end
  
  def get_attribute_values
    @attribute_values ||= self.attribute_values
  end
  
  def get_value_from_field_id(field_id)
    values = get_attribute_values
    value = values.detect {|value| value.attribute_field_id == field_id} rescue nil
    value ? value : self.attribute_values.build
  end

  def self.from_id(id)
    User.find(id) rescue nil
  end
  
end
