# Audience plugin for Vellum
"""The Audience plugin provides an abstract object type, Audience,
which is used to contain responses to your posts. These responses
might include comments, pingbacks, or trackbacks, each implemented
by their own plugin.

An Audience object has the following fields:
  id
    A unique ID
  entryid
    The ID of the entry to which this response is attached
  ref
    Some text which identifies this response (for pingbacks it might
    be the pinging URL, for comments it might be the commenter's name)
  type
    A string indicating which type of response this is (e.g., "comment")
  text
    The body text of the response
  posted
    A time.time() value indicating when this response was saved
  custom1
  custom2
  custom3
    Some custom fields, which the particular response plugin can use in
    any way it sees fit.

"""

from vellum.vellumObject import vellumObject
import vellum.config,vellum.Entry
import time,bsddb,os
try:
    import cPickle as pickle
except:
    import pickle

class Audience(vellumObject):
    id = None
    entryid = None
    ref = ''
    type = ''
    text = ''
    posted = None
    custom1 = None
    custom2 = None
    custom3 = None

    def save(self):
        self.setMyID()
        if not self.posted: self.posted = time.time()
        vellumObject.save(self)

dbdir = vellum.config.get("DatabaseDir")
if not dbdir:
    raise "There is no DatabaseDir listed in the config file"

Audience.db = bsddb.hashopen(os.path.join(dbdir,"audience"),"c")

def all_audience():
    return map(get_audience_obj,Audience.db.keys())

def get_audience_obj(id):
    "Gets one individual Audience object by ID"
    sid = str(id)
    if Audience.db.has_key(sid):
        k,v = Audience.db.set_location(sid)
        return pickle.loads(v)
    else:
        return None

def get_audience(entry,type=None):
    "Gets all audiences (possibly of a specified type) for the passed entry"
    ep = filter(lambda x,i=entry.id:str(x.entryid)==str(i),all_audience())
    if type: ep = filter(lambda x,type=type: x.type==type,ep)
    ep.sort(lambda x,y:cmp(y.posted,x.posted))
    return ep

vellum.Entry.Entry.audience = get_audience

__pluginname__ = "Audience framework"
__description__ = """The Audience framework makes it easy to write plugins
to handle responses to your posts, such as comments, pingbacks, or
trackbacks."""