"""
$Id: note.py 29832 2007-05-29 19:19:08Z dbinger $
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/note.py $
"""
from dulcinea.attachable import Attachable
from durus.btree import BTree, BNode
from durus.persistent import PersistentObject
from qp.lib.spec import specify, string, sequence, add_getters_and_setters
from qp.lib.spec import init, Specified, Mixin, datetime_with_tz
from qp.pub.common import get_connection, get_user, site_now
from qp.pub.user import User

def get_note_mapping():
    return get_connection().get_root().get('note_mapping')

class Note (PersistentObject, Specified, Attachable):

    text_is = (string, None)
    timestamp_is = (datetime_with_tz, None)
    user_is = (User, None)
    title_is = (string, None)

    def __init__(self, text=None):
        Attachable.__init__(self)
        init(self, text=text)

    def set_timestamp(self, value=None):
        specify(self, timestamp=value or site_now())

    def set_user(self, user=None):
        specify(self, user=user or get_user())

    def is_empty(self):
        return not bool(self.text or self.get_attachments())

add_getters_and_setters(Note)

class Notable (Mixin):

    note_is = (Note, None)

    def __init__(self, note=None):
        self.set_note(note)

add_getters_and_setters(Notable)


class NoteMapping (BTree, Specified):

    root_is = sequence((string, Note), BNode)

    def add_note(self, note):
        title = note.get_title()
        if title.lower() not in self:
            self[title.lower()] = note

    def get_note(self, title, default=None):
        if title:
            return self.get(title.lower(), default=default)
        return default

    def remove_note(self, note):
        del self[note.get_title().lower()]

