########################################
# The contents of this file are subject to the MLX PUBLIC LICENSE version
# 1.0 (the "License"); you may not use this file except in
# compliance with the License.
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Source Code is "compClust", released 2003 September 03.
# 
# The Original Source Code was developed by the California Institute of
# Technology (Caltech).  Portions created by Caltech are Copyright (C)
# 2002-2003 California Institute of Technology. All Rights Reserved.
########################################
#
#       Author: Lucas J. Scharenbroich
# 
# Original Implementation:  July 10 by Lucas Scharenbroich
#
##########################################################################

"""
A very loose data structure.  Simply a bunch of unordered data nodes.

A collection data structure is simply an unordered collection of nodes.
This is simply a container to hold and keep track of a bunch of nodes,
each identified by a unique key.
"""

from Node import *

class CollectionIterator:
    def __init__(self, collection):
        self.collection = collection
        self.index = 0

    def first(self):
        self.index = 0
        return self.__get()
                
    def last(self):
        self.index = len(self.collection.nodes) - 1
        return self.__get()
        
    def next(self):
        self.index += 1
        return self.__get()

    def __get(self):
        max = len(self.collection.nodes)
        if max > self.index:
            key = self.collection.nodes.keys()[self.index]
            return self.collection.nodes[key]
        else:
            return None
        

class Collection:
    def __init__(self):
        self.nodes = {}
        
    def iterator(self):
        return CollectionIterator(self)

    def clear(self):
        self.nodes.clear()

    def addNode(self, node):
        self.nodes[node.key()] = node

    def removeNode(self, key):
        if self.exists(key):
            del self.nodes[key]

    def keys(self):
        return self.nodes.keys()

    def values(self):
        return self.nodes.values()

    def items(self):
        return self.nodes.items()

    def exists(self, key):
        return self.nodes.has_key(key)

    def find(self, key):
        return self.nodes.get(key, None)
