""" QueueDict.py

Sorted container of SummaryItems
"""
__copyright__ = "Copyright (c) 2002-2005 Free Software Foundation, Inc."
__license__ = """GNU General Public License

This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA. """

from bisect import insort

class ItemQueue(dict):
    def __init__(self):
        dict.__init__(self)
        self._reverse = 0
        self._keys = list()

    def __delitem__(self, key):
        try:
            self._keys.remove(key)
            dict.__delitem__(self, key)
        except KeyError:
            raise "FeedQD: No Such Key %d" % key

    def __iter__(self):
        return self.iteritems()

    def __contains__(self, item):
        return item in self.itervalues()

    def __setitem__(self, key, value):
        self.append(value)

    def _set_reverse(self, reverse):
        self._reverse = reverse

    def _get_reverse(self):
        return self._reverse

    sort_order = property(_get_reverse, _set_reverse)

    def append(self, item):
        if item.id not in self._keys:
            insort(self._keys, item.id)
        dict.__setitem__(self, item.id, item)

    def replace(self, item):
        self.append(item)
        k = self.keys()
        item = None
        for iid in reversed(k):
            item = self[iid]
            if item.sticky:
                continue
            else:
                del self[iid]
                break
        return item

    def clear(self):
        dict.clear(self)
        del self._keys[:]

    def keys(self):
        if self._reverse:
            return sorted(self._keys, reverse=True)
        return self._keys

    def values(self):
        return map(self.get, self.keys())

    def iteritems(self):
        def sorteditems():
            for k in self.keys():
                yield (k, self[k])
        return sorteditems()

    def iterkeys(self):
        def sortedkeys():
            for k in self.keys():
                yield k
        return sortedkeys()

    def itervalues(self):
        def sortedvalues():
            for k in self.keys():
                yield self[k]
        return sortedvalues()

    def items(self):
        return [item for item in self.iteritems()]

    def index(self, key):
        try:
            idx = self.keys().index(key)
        except (IndexError, ValueError):
            idx = None
        return idx
