from wxpy.utils import match_attributes, match_text


class Messages(list):
    """
    多条消息的合集，可用于记录或搜索
    """

    def __init__(self, msg_list=None, bot=None, max_history=None):
        if msg_list:
            super(Messages, self).__init__(msg_list)
        self.bot = bot
        self.max_history = max_history

    def append(self, msg):
        if isinstance(self.max_history, int) and self.max_history > 0:
            del self[:-self.max_history + 1]
        return super(Messages, self).append(msg)

    def search(self, keywords=None, **attributes):
        """
        搜索消息记录

        :param keywords: 文本关键词
        :param attributes: 属性键值对
        :return: 所有匹配的消息
        """

        def match(msg):
            if not match_text(msg.text, keywords):
                return
            if not match_attributes(msg, **attributes):
                return
            return True

        return Messages(filter(match, self), bot=self.bot, max_history=self.max_history)
