"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/item.py $
$Id: item.py 30928 2008-07-30 20:15:05Z rmasse $
"""
from dulcinea.base import DulcineaPersistent
from dulcinea.common import format_date
from dulcinea.timestamped import Timestamped, reverse_timestamp_sorted
from qp.lib.keep import Keyed, Keep
from qp.lib.spec import add_getters_and_setters, string, boolean, init


class Item(DulcineaPersistent, Keyed, Timestamped):

    title_is = (string, None)
    approved_is = boolean

    def __init__(self):
        assert self.__class__ is not Item, "abstract class"
        Keyed.__init__(self)
        Timestamped.__init__(self)
        init(self, approved=False)

    def absorb(self, other):
        assert self.__class__ is other.__class__
        for key, value in other.__getstate__().items():
            if key != 'key':
                setattr(self, key, value)
                
    def get_search_text(self):
        return ' '.join(self.get_search_text_fields())

    def get_search_text_fields(self):
        return [self.get_title() or '', format_date(self.get_timestamp())]

    def is_approved(self):
        return self.approved

    def can_modify(self, user):
        return user.is_admin()

add_getters_and_setters(Item)


class ItemFolder(DulcineaPersistent, Keep):

    def delete(self, item):
        del self.get_mapping()[item.get_key()]

    def get_items(self):
        """() -> [Item]
        """
        return list(self.get_mapping().values())

    def get_recent_items(self, count=None, include_unapproved=False):
        """(count : int = None, include_unapproved : bool = False) -> [Item]

        Return the 'count' most recent items.  If 'include_unapproved' is True,
        both un-approved and approved items are returned.
        The list returned is in reverse-chronological order by timestamp.
        """
        return reverse_timestamp_sorted(
            [item for item in self.get_mapping().itervalues()
             if item.is_approved() or include_unapproved])[:count]
             
    def get_to_oldest_date(self, oldest_date, **kwargs):
        if oldest_date is not None:
            return [item for item in self.get_recent_items(**kwargs)
                    if oldest_date <= item.get_timestamp()]
        return self.get_recent_items(**kwargs)
