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

  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :registerable, :validatable #, :timeoutable
  
  mount_uploader :avatar, AvatarUploader
  
  field :admin, :type => Boolean, :default => true
  field :active_role
  field :email
  field :cache_dept,type: Hash
  field :status_record,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
  has_one :desktop, :autosave => true, :dependent => :destroy
  has_many :other_accounts, :autosave => true, :dependent => :destroy
  # has_many :journals, :autosave => true, :dependent => :destroy
  # has_many :papers, :autosave => true, :dependent => :destroy
  has_and_belongs_to_many :sub_role_tags

  has_and_belongs_to_many :statuses
  has_and_belongs_to_many :roles
  has_and_belongs_to_many :sub_roles
  accepts_nested_attributes_for :attribute_values, :allow_destroy => true 

  before_create :initialize_desktop
  before_save :rebuild_status_record
  before_save :save_roles
  scope :remote_account, where(:nccu_id.ne => nil)
  scope :not_guest_user, all_of(:name.ne => "guest")

  # validates_uniqueness_of :email,:message=> I18n.t("devise.registrations.email_not_unique")
  
  # def new_attribute_values=(vars)
  #   binding.pry
  # end
  # def new_attribute_values(vars)
  #   binding.pry
  # end

  ## # class << self
  ##   def initialize
  ##       self.define_method("asd"){ p "hi"}
  ##       sub_roles.each do |sr| 
  ##       sr_ids = sr.attribute_fields.collect{|t| t.id.to_s}
  ##       self.define_method("attribute_values_for_"+sr.key.to_s) { 
  ##         AttributeValue.where(user_id: id ).in(attribute_field_id: sr_ids)
  ##       }
  ##     end      
  ##     yield self 
  ##   end

  # end

  # def initialize
  #   binding.pry
  #   # yield self
  # end

  def get_attribute_value(attribute_field)
    attribute_values.where(attribute_field_id: attribute_field.id).first 
  end

  def get_sub_roles_by_role(role)
    sub_roles.where(role_id: role.id)
  end

  def disable_sub_role=(var)
    var[:id].each do |id,val|  
      # binding.pry if id == '5052c5b22b5c49ab02000004'
      if (val=="true")
        self.sub_roles = self.sub_roles.reject{|t| t.id.to_s==id}
      elsif(val=="false")
        self.sub_roles << SubRole.find(id)
      end
    end
  end



  def set_sub_role(sub_role_id,status_id)
    self.status_record.merge!(Hash[sub_role_id,status_id])
  end

  # def get_status(*params)
  #   param = params[0]
  #   case param.class.to_s
  #   when 'String'
  #     sr = ::SubRole.find sub_role_id
  #   when 'Hash'
  #     sr = ::SubRole.first({conditions:{key: param[:key]}})
  #   end
  #   if self.sub_roles.include?(sr)
  #     return ::Status.find(status_record.fetch(sr.id.to_s))
  #   else
  #     nil
  #   end
  # end
  def new_attribute_values=(fields)
    fields.each do |key,field|
      self.attribute_values.build(field)
    end
  end

  def self.find_by_status_and_sub_role_key(sub_role_key,status_key) #Query for users by using specific sub_role  and status key
    sr = ::SubRole.first({conditions: { key: sub_role_key }})
    status = ::Status.first({conditions:{role_id: sr.role.id,key: status_key}})
    find_by_subrole_and_status(sr.id,status.id)
  end

  def self.find_by_subrole_and_status(sub_role_id,status_id) #Query for users by using specific sub_role  and status key by within ID
    User.not_guest_user.where("status_record.#{sub_role_id}" => status_id,:sub_role_ids.in => [ sub_role_id ])
  end

  def self.find_by_status(status_id)
    status = ::Status.find status_id
    ::SubRole.where({role_id: status.role.id.to_s,disabled: false}).collect{|sr|
      find_by_subrole_and_status(sr.id.to_s,status_id)
    }.uniq!
  end

  def create_dept_cache
    dept_hash = {}

    VALID_LOCALES.each  do |loc|
      locale = loc.to_sym
      dept_hash[locale] = sub_roles.collect{|sr| sr.title}.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
  
  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
      full_name = "#{last_name} #{first_name}"

      if full_name.strip.empty?
        full_name = email
      end

      return full_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 : nil
  end

  def self.from_id(id)
    User.find(id) rescue nil
  end
  
  def initialize_desktop
   self.build_desktop(desktop_widget_ids: DesktopWidget.all.collect{|widget| widget.id})
  end
  
  protected
    def save_roles
      self.roles = self.sub_roles.collect{|t| t.role}.uniq
    end


  def rebuild_status_record
    self.status_record = {}
    self.attribute_values.reject{|t| t.key!='status'}.each do |status|
      # binding.pry
      set_sub_role(status.attribute_field.attribute.id.to_s,status[:value]) rescue nil
    end
  end

end