#!/usr/bin/python

from message                    import Message

class Messages(object):
    # __init__
    #
    # Initialize the instance from a Launchpad bug.
    #
    def __init__(self, tkbug):
        self.__tkbug                = tkbug
        self.__commit_changes       = tkbug.commit_changes
        self.__messages             = None

        self.__filter_since_status_change = False
        self.__filter_by_max_age    = None
        self.__filtered_messages    = None

    def filtered_messages(self):
        if self.__filtered_messages is None:
            self.__filtered_messages = list(self.__iter__())
        return self.__filtered_messages

    # __len__
    #
    def __len__(self):
        return len(self.filtered_messages())

    # __getitem__
    #
    def __getitem__(self, key):
        messages = self.filtered_messages()
        return messages[key]

    # __iter__
    #
    def __iter__(self):
        self.__fetch_if_needed()
        for msg in self.__messages:
            m = Message(self.__tkbug, msg)
            if self.__filter_by_max_age:
                if m.age > self.__filter_by_max_age:
                    continue
            elif self.__filter_since_status_change:
                if m.age > self.__tkbug.status_age:
                    continue
            yield m

    # __contains__
    #
    def __contains__(self, item):
        return item in self.__iter__()

    # __fetch_if_needed
    #
    def __fetch_if_needed(self):
        if self.__messages == None:
            self.__messages = self.__tkbug.lpbug.messages_collection

    def set_filter_by_max_age(self, days):
        '''Only include messages posted within the given number of days'''
        self.__filter_by_max_age = days
        self.__filtered_messages = None

    def set_filter_since_status_change(self):
        '''Only include messages created since the status was changed'''
        self.__filter_since_status_change = True
        self.__filtered_messages = None

    # non_owner_count
    #
    def non_owner_count(self):
        '''Number of messages by someone other than the original reporter'''
        count = 0
        for message in self.__iter__():
            if message.owner != self.__tkbug.owner:
                count += 1
        return count

    # owners
    #
    @property
    def owner_usernames(self):
        '''List of People who have posted one or more of these Messages'''
        owners = {}
        for message in self.__iter__():
            owners[message.owner.username] = 1
        return owners.keys()

# vi:set ts=4 sw=4 expandtab:
