# Copyright (c) 1996, 1997, 1998 The Regents of the University of California.
# All rights reserved.  See legal notices for full text and disclaimer.

"""
HistoryCollector
    The constructor for Tag takes a HistoryCollector as an argument.
"""

class HistoryCollector:
    """ History()
    A history engine that holds tags which in turn direct the collection of items
    to history media, such as text files, database files, or memory.
    """
    def __init__ (self):
        self.taglist = []

    def tag (self, tagname):
        "Get the tag named tagname."
        p = self.position (tagname)
        return self.taglist[p]

    def position (self, tagname):
        "Get the position in the taglist of tagname."
        s = self.taglist
        for j in range(len(s)):
            if tagname == s[j].name:
                return j
        raise NameError, "No such tagname in this collector: " + tagname

    def tagnames (self):
        "Names of the tags in this HistoryCollector."
        t = []
        for x in self.taglist:
            t.append (x.name)
        return t

    def add (self,tag,position = -1):
        "Add a tag to this history collector in the desired position."
        self.taglist.insert (position, tag)

    def delete (self,tagname):
        "Remove a tag from this history collector."
        p = self.position (tagname)
        del self.tagslist[p]

    def sample (self, cycle, time, tagname = ''):
        "Collect a sample from every item in the tag(s) if their condition is true."
        if tagname =='':
            ts = self.taglist
        else:
            ts = [tagname]
        for t in ts:
            t.sample (cycle, time)

    def sample_final (self, cycle, time, tagname = ''):
        "Collect a sample from every item in the tag(s) is their final condition is true."
        if tagname == '':
            ts = self.taglist
        else:
            ts = [tagname]
        for t in ts:
            t.sample_final (cycle, time)

    def check (self, tagname = ''):
        "Check each item in the tag(s) and print a list of those that fail when collected."
        if tagname == '':
            ts = self.taglist
        else:
            ts = [tagname]
        print "Check showing failing items, by tag:"
        for t in ts:
            print t.name, ": ", t.failing ()
        print """End of check. Note that items may fail because they
refer to objects that do not yet exist, and the item may therefore not
actually fail when it is time to evaluate it."""

    def __repr__ (self):
        result = "History collector:\n"
        for t in self.taglist:
            result = result + "\t" + `t` 
        return result

    __str__ = __repr__

