class Authorization
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title

  belongs_to :module_app

  has_and_belongs_to_many :roles
  has_and_belongs_to_many :sub_roles

  delegate :update_auth_approval_users, :update_auth_manager_users, :update_auth_sub_manager_users, to: :module_app, prefix: true, allow_nil: true

  after_save :update_module_app


  def add_roles(roles)
  	users = []
  	roles = Array(roles)
    add_operation(:roles, roles)
    sub_roles = [] 
    roles.each{|role| role.sub_roles.each{|sub_role| sub_roles << sub_role.id}}
    add_operation(:sub_roles, sub_roles)
    roles.each{|role| role.users.where(admin: false).each{|user| users << user}}
		add_users(users, false)
  end
  
  def add_sub_roles(sub_roles)
  	users = []
  	sub_roles = Array(sub_roles)
    add_operation(:sub_roles, sub_roles)
    sub_roles.each do |sub_role| 
			self.roles << sub_role.role unless self.roles.include?(sub_role.role)
    	sub_role.users.where(admin: false).each{|user| users << user}
    end
		add_users(users, false)
  end
  
  def add_users(users, with_parents = true)
  	users = Array(users)
    add_operation(:authorized_users, users)
    users.each do |user|
    	user.roles.each do |role|
	    	self.roles << role unless self.roles.include?(role)
    	end
    	user.sub_roles.each do |sub_role|
	    	self.sub_roles << sub_role unless self.sub_roles.include?(sub_role)
    	end
    end if with_parents
   	self.save
  end

  def remove_roles(roles)
  	users = []
  	sub_roles = []
  	roles = Array(roles)
  	remove_operation(:roles, roles)
 		roles.each do |role|
 			role.sub_roles.each{|sub_role| sub_roles << sub_role}
 			role.users.where(admin: false).each{|user| users << user}
 		end
		remove_operation(:sub_role_ids, sub_roles)
		remove_operation(:authorized_user_ids, users)
		add_roles(self.roles)
  end

  def remove_sub_roles(sub_roles)
  	users = []
  	sub_roles = Array(sub_roles)
  	remove_operation(:sub_roles, sub_roles)
  	sub_roles.each do |sub_role|
  		users << sub_role.users.where(admin: false)
  	end
		remove_operation(:authorized_user_ids, users)
		add_roles(self.roles)
  end

  def remove_users(users)
  	users = Array(users)
  	remove_operation(:authorized_user_ids, users)
   	self.save
  end

  protected

  def add_operation(db_field, objs)
   	objs.each do |obj|
	   	self.send(db_field) << obj unless self.send(db_field).include?(obj)
   	end
  end  

  def remove_operation(db_field, obj)
    self.write_attribute(db_field, self.send(db_field) - obj.map{|y| y.id})
  end

  private

  def update_module_app
  	case self._type
  	when "AuthApproval"
  		self.module_app_update_auth_approval_users
  	when "AuthManager"
  		self.module_app_update_auth_manager_users
  	when "AuthSubManager"
  		self.module_app_update_auth_sub_manager_users
  	end
  end
end