########################################################################
#
# File Name:            ResourceDict.py
#
# Documentation:        http://docs.4suite.org/4Rdf/ResourceDict.py.html
#
"""
RDF Resource represented as a dictionary
WWW: http://4suite.org/4RDF         e-mail: support@4suite.org

Copyright (c) 1999 Fourthought, Inc., USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""
#"


def CreateResourceDict(model,rid,created=None):
    created = created or {}
    if created.has_key(rid):
        return created[rid]
    rt = ResourceDict(model,rid,created)
    created[rid] = rt
    return rt

class ResourceDict:
    def __init__(self,model,rid,created):
        self._model = model
        self._rid = rid
        self._created = created
        


    def __repr__(self): return  '<RDF ResourceDict at %s: [URI: %s]>'%(id(self), self._rid)

    def __cmp__(self, dict):
        if isinstance(dict, ResourceDict):
            return cmp(self._rid, dict._rid)
        return 0
    def __len__(self):
        return len(self.keys())
                
    def __getitem__(self, key):
        rt = self._model.complete(self._rid,key,'')
        if len(rt) == 0:
            raise KeyError(key)
        else:
            res = []
            for r in rt:
                if len(self._model.complete(r.object,'','')) > 0:
                    res.append(CreateResourceDict(self._model,r.object,self._created))
                else:
                    res.append(r.object)
        return res
    
    def __setitem__(self, key, item):
        self._model.add(self._model._mapStatements([(self._rid,key,item,'')]))

    def __delitem__(self, key):
        stmts = self._model.complete(self._rid,key,'')
        self._model.remove(stmts)

        
    def clear(self):
        stmts = self._model.complete(self._rid,'','')
        self._model.remove(stmts)
    
    def copy(self):
        raise "Not Supported"

    def keys(self):
        rt = self._model.complete(self._rid,'','')
        keys = []
        for r in rt:
            if r.predicate not in keys:
                keys.append(r.predicate)
        return keys

    def items(self):
        res = []
        for k in self.keys():
            res.append((k,self[k]))
        return res

    def values(self):
        res = []
        for k in self.keys():
            res.append(self[k])
        return res

    def has_key(self, key):
        return key in self.keys()
    def update(self, dict):
        raise "Not Supported"

    def get(self, key, failobj=None):
        if self.has_key(key):
            return self[key]
        return failobj

