class AppAuth
  include Mongoid::Document
  include Mongoid::Timestamps
 # after_save :update_block_list,:update_privilage_list
  
  field :title
  field :token
  field :all ,type: Boolean,default: false
  belongs_to :module_app
  
  belongs_to :users
  # belongs_to :users,as: :block_users, :inverse_of => :privilege_apps
  has_and_belongs_to_many :blocked_users,  :inverse_of => nil, :class_name => "User"
  has_and_belongs_to_many :privilege_users,  :inverse_of => nil, :class_name => "User"


  has_and_belongs_to_many :roles
  
  def add_user_to_black_list user
    unless self.blocked_users.include?(user)
      self.blocked_users << user
      self.save!
    else
      false #should put error message for user existed in list already
    end
  end
  
  
  def remove_user_from_black_list user
    if self.blocked_users.include? user
      self.blocked_users.delete user
      self.save!
    else
      false #should put error message for user not existed in list
    end
  end
  
  
  def add_user_to_privilege_list user
    unless self.privilege_users.include? user
      self.privilege_users << user
      self.save!
    else
      false #should put error message for user existed in list already
    end
  end
  
  
  def remove_user_from_privilege_list user
    if self.privilege_users.include? user
      self.privilege_users.delete user
      self.save!
    else
      false #should put error message for user not existed in list
    end
  end
  
  def auth_users
    if self.all?
      User.all.entries
    else
      ary= self.roles.collect do |role|
        role.users
      end
      ary << self.privilege_users
      ary.flatten!  
    end
  end
  
  def auth_users_after_block_list
    auth_users - self.blocked_users
  end
  
 # protected
  

end