from Ft.Server.Server import FtServerServerException, Error
from Ft.Server.Common import ResourceTypes
from Ft.Server import FTSERVER_NAMESPACE
from Ft.Xml.XLink import XLINK_NAMESPACE
from Ft.Server.Server.Drivers.FtssDriver import DataStoreContainer
import cPickle as pickle

try:
    # For Pythons w/distutils pybsddb
    from bsddb3.db import *
except ImportError:
    # For Python 2.3
    from bsddb.db import *
    
from dbxml import *

from Util import GetContainer,GetDB

FTSS_CONTAIMENT_DB_NAME = 'ftss_containment.db'
columns = ['parent','child']


class BerkeleyDBContainer(DataStoreContainer):
    """
    Implements simple containment as a 'parent' -> [child1,child2,childn] key/value Berkeley Database
    """
    def __init__(self):
        pass
    
    def initialize(self):
        pass
    
    def fetchChildren(self,parent):
        """
        Returns a list of child uris for the given parent.  Parent is a PathImp
        """
        #print self._dBs
        txn,db=self._dBs[FTSS_CONTAIMENT_DB_NAME]
        children = db.get(str(parent.absolutePath),None,txn=txn)
        children = children and pickle.loads(children) or []
        #print "children of %s: %s"%(parent.absolutePath,children)
        return children
        
    def manageChildren(self,parent,child,add=True):
        """
        Adds/remove the child specified by the given path to the parent (path - a PathImp)
        
        """
        txn,db=self._dBs[FTSS_CONTAIMENT_DB_NAME]
        parentPath = parent.absolutePath
        children = db.get(str(parentPath),None,txn=txn)
        children = children and pickle.loads(children) or []
        if add:
            children.append(child)
        else:            
            children.remove(child)
        db.put(str(parentPath),pickle.dumps(children,1),txn=txn)

    
