"""$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/persistent_list.py $
$Id: persistent_list.py 21569 2003-05-09 00:31:47Z abenard $

Provides the PersistentList class, an analogue to ZODB's PersistentMapping
that ZODB forgot.  Hopefully this module will go away someday, to be
replaced by ZODB.PersistentList.
"""

import UserList
from dulcinea.base import DulcineaPersistent


class PersistentList(DulcineaPersistent, UserList.UserList):
    """Wrapper class for lists that sets ._p_changed correctly.

    Instance attributes:
      data : [any]
    """

    def __init__(self, initlist=None):
        UserList.UserList.__init__(self, initlist)

    def copy(self):
        return self.__class__(self.data)

    def __setitem__(self, i, item):
        self._p_changed = 1
        self.data[i] = item

    def __delitem__(self, i):
        self._p_changed = 1
        del self.data[i]

    def __setslice__(self, i, j, other):
        self._p_changed = 1
        i = max(i, 0); j = max(j, 0)
        if isinstance(other, UserList.UserList):
            self.data[i:j] = other.data
        elif isinstance(other, type(self.data)):
            self.data[i:j] = other
        else:
            self.data[i:j] = list(other)

    def __delslice__(self, i, j):
        self._p_changed = 1
        i = max(i, 0); j = max(j, 0)
        del self.data[i:j]

    def append(self, item):
        self._p_changed = 1
        self.data.append(item)

    def insert(self, i, item):
        self._p_changed = 1
        self.data.insert(i, item)

    def pop(self, i=-1):
        self._p_changed = 1
        return self.data.pop(i)

    def remove(self, item):
        self._p_changed = 1
        self.data.remove(item)

    def reverse(self):
        self._p_changed = 1
        self.data.reverse()

    def sort(self, *args):
        self._p_changed = 1
        apply(self.data.sort, args)

    def extend(self, other):
        self._p_changed = 1
        if isinstance(other, UserList.UserList):
            self.data.extend(other.data)
        else:
            self.data.extend(other)

    def __repr__(self):
        return '<%s at %x: %d item(s)>' % (self.__class__.__name__,
                                           id(self), len(self.data))

    def __cmp__(self, other):
        # ExtensionClass does not support richcomps.  UserList only provides
        # richcomps. :-(
        return cmp(self.data, other)


# class PersistentList
