from .interfaces import INotificationsQueues
from Acquisition import Explicit
from BTrees import OOBTree
from BTrees.LOBTree import LOBTree
from persistent import Persistent
from zope.interface import implementer

import logging
import time

logger = logging.getLogger(__name__)


class AppendableLOBTree(LOBTree):
    """BBB: Implement append to LOBtrees to make it work like lists.

    Obsolete: it was used by the old notifications system and it is kept here
    to not have broken objects in the database.

    TODO: We should get rid of this code once we will decide the old notifications
    queue can be removed
    (i.e. when we will delete portal.ploneintranet_notifications._users)
    """

    def append(self, value):
        """We append to the LOBtree value generating a key based on the current
        time."""
        key = int(time.time() * 1.0e6)
        while key in self:
            key = key + 1
        # Store the key in the object so that we can generate a URL to fetch it later
        # XXX This is pretty hackish, but the alternative is to rewrite a lot of code
        value.id = key
        self[key] = value

    def as_tuple(self, limit=None):
        """Return the values as a tuple."""
        keys = sorted(self)
        if limit is not None:
            keys = keys[:limit]
        return tuple(self[key] for key in keys)


@implementer(INotificationsQueues)
class Queues(Persistent, Explicit):
    """Stores queues for each user. Users are referenced as string userids.

    Return values are BTrees.OOBTree.OOTreeSet iterables.
    """

    def __init__(self, context=None):
        self._users = OOBTree.OOBTree()
