from . import EM


class Statistics(object):
    """Hierarchic message statistics representation
    field - name of the attribute summarized on this level
    id - attribute value
    count - matching messages number
    children - list of Statistics objects giving finer granularity,
    e.g. in case self is check level statistics, children might contain
    description level statistics
    """

    def __init__(self, field, id, count=None, children=None, **kwargs):
        self.field = field
        self.id = id
        self._count = count
        self._attrs = kwargs

        self.children = [] if children is None else children

    def get_ET(self):
        ret = getattr(EM, self.field)(id=self.id,
                                      count=self.count,
                                      **{key: self.attr_stat(key) for key in self._attrs})
        for child in self.children:
            ret.append(child.get_ET())
        return ret

    @property
    def count(self):
        if self._count is not None:
            return self._count
        else:
            return sum(child.count for child in self.children)

    def attr_stat(self, key):
        if self._attrs[key] is not None:
            return self._attrs[key]
        else:
            return sum(child.attr_stat(key) for child in self.children)
