########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Rdf/Container.py,v 1.4 2005/02/26 01:18:34 jkloth Exp $
"""
Classes for RDF Container objects

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft.Rdf import RDF_MS_BASE, RdfException
from Ft.Rdf.Resource import Resource


class Container(Resource, list):
    """
    Base class for Bag, Sequence, and Alternative,
    as defined in sec. 3.1 of the 1999 RDF Model and Syntax Spec.
    """
    def __init__(self, className, uri=None, contents=None):
        #if uri == None:
        #    uri = model.generateUri()
        contents = contents or []
        Resource.__init__(self, uri)
        list.__init__(self, contents)
        self.className = className
        return

    def __repr__(self):
        st = '<%s at %s URI="%s": '%(self.className, id(self),self.uri)
        if len(self) < 1:
            st += 'empty'
        else:
            st += '[%s]' % ', '.join([i for i in self])
        st += '>'
        return st

    def append(self, obj):
        if not isinstance(obj, (str, unicode)):
            raise RdfException(RdfException.INVALID_CONTAINER_ITEM_TYPE, obj)
        else:
            return list.append(self, obj)


class Bag(Container):
    """
    An unordered list of resources or literals,
    as defined in sec. 3.1 of the 1999 RDF Model and Syntax Spec.
    """
    def __init__(self, uri=None, contents=None):
        return Container.__init__(self, 'Bag', uri, contents)

class Sequence(Container):
    """
    An ordered list of resources or literals,
    as defined in sec. 3.1 of the 1999 RDF Model and Syntax Spec.
    """
    def __init__(self, uri=None, contents=None):
        return Container.__init__(self, 'Seq', uri, contents)

class Alternative(Container):
    """
    A list of resources or literals that represent alternatives
    for the (single) value of a property,
    as defined in sec. 3.1 of the 1999 RDF Model and Syntax Spec.
    """
    def __init__(self, uri=None, contents=None):
        return Container.__init__(self, 'Alt', uri, contents)


baseLength = len(RDF_MS_BASE + '_')

def SortStatements(left, right):
    leftCtr = int(left.predicate[baseLength:])
    rightCtr = int(right.predicate[baseLength:])
    return cmp(leftCtr, rightCtr)
