# -*- coding: utf-8 -*-
# Elisa - Home multimedia server
# Copyright (C) 2006-2008 Fluendo Embedded S.L. (www.fluendo.com).
# All rights reserved.
#
# This file is available under one of two license agreements.
#
# This file is licensed under the GPL version 3.
# See "LICENSE.GPL" in the root of this distribution including a special
# exception to use Elisa with Fluendo's plugins.
#
# The GPL part of Elisa is also available under a commercial licensing
# agreement from Fluendo.
# See "LICENSE.Elisa" in the root directory of this distribution package
# for details on that license.


__maintainer__ = 'Lionel Martin <lionel@fluendo.com>'

import gc

class ReportTools:

    def get_instance_infos(self, snapshot=None, min_count = 5,
                           class_filter=None):
        """
        return a dict:
        key: classname of the instance
        value: (refcount, instances) 
        """
        d = {}
        gc.collect()
        all_objects = gc.get_objects()

        def class_filter_function(obj):
            return isinstance(obj, class_filter)

        if class_filter != None:
            all_objects = filter(class_filter_function, all_objects)

        for obj in all_objects:
            try:
                if hasattr(obj, '__class__'):
                    class_name = obj.__class__
                else:
                    class_name = str(obj)[0:50]
                if d.has_key(class_name):
                    refcount = d[class_name][0] + 1
                    instances = d[class_name][1]
                    instances.append(obj)
                    d[class_name] = (refcount, instances)
                else:
                    refcount = 1
                    instances = [obj]
                    d[class_name] = (refcount, instances)
            except Exception, e:
                print e
                pass

        # apply snapshot and cut the dict
        for key in d.keys():
            refcount = d[key][0]
            if refcount > min_count:
                if snapshot != None and snapshot.has_key(key):
                    new_refcount = refcount - snapshot[key][0]
                    if new_refcount == 0:
                        del d[key]
                    else:
                        d[key] = (new_refcount, d[key][1])
            else:
                del d[key]

        return d
