module OrbitApp
  module ModuleAppMembershipTools
      def is_manager?(user)
        if user.nil?
          return false
        else
          m_users = managing_users
          if m_users.blank?
            false
          else
            m_users.include?(user)  
          end
        end
      end
      
      def is_sub_manager?(user)
        if user.nil?
          return false
        else # when user is guest
          s_m_users = sub_managing_users
          result = false
          if s_m_users.blank?
            result = false
          else
            result = s_m_users.include?(user) 
          end
          result || is_manager?(user)
        end
      end
      
      def managing_users
        self.managers.collect{ |t| t.user }
      end
      
      def sub_managing_users
        self.sub_managers.collect{ |t| t.user }
      end
      
      def assign_manager(user,assigner)
        manager = AppManager.first(conditions: {managing_app_id: self.id,user_id: user.id}) rescue nil    
        if manager.nil? 
          manager = self.managers.create(:user_id => user.id,:rule_creator_id => (assigner.id rescue nil))
        end
        manager
      end
      
      def assign_sub_manager(user,assigner)
        submanager = AppManager.first(conditions: {sub_managing_app_id: self.id,user_id: user.id}) rescue nil
        if submanager.nil? && !self.managing_users.include?(user)
          submanager = self.sub_managers.create(:user_id => user.id,:rule_creator_id => (assigner.id rescue nil) )
        end
        submanager
      end
      
      def remove_manager(user)
        manager = AppManager.first(conditions: {managing_app_id: self.id,user_id: user.id}) rescue nil
        if manager
          manager.destroy
        else
          false
        end
      end
      
      def remove_sub_manager(user)
        submanager = AppManager.first(conditions: {sub_managing_app_id: self.id,user_id: user.id}) rescue nil
        if submanager
          submanager.destroy
        else
          false
        end
      end
  end
end