# copyright (C) 1997-2006 Jean-Luc Fontaine (mailto:jfontain@free.fr)
# this program is free software: please read the COPYRIGHT file enclosed in this package or use the Help Copyright menu

# $Id: history.tcl,v 1.4 2006/01/28 19:16:59 jfontain Exp $


namespace eval history {

    proc remember {array row column value {seconds {}}} {
        variable data

        if {$seconds eq ""} {set seconds [clock seconds]}
        set data($array,$row,$column,$seconds) $value
    }

    proc list {array row column} {                                                         ;# of seconds, value, seconds, value, ...
        variable data

        foreach {name value} [array get data $array,$row,$column,*] {
            set values([lindex [split $name ,] end]) $value
        }
        set list {}
        foreach seconds [lsort -integer [array names values]] {
            lappend list $seconds $values($seconds)
        }
        return $list
    }

    proc clean {} {                                                                        ;# remove old and disappeared arrays data
        variable data

        foreach name [array names data] {
            set array([lindex [split $name ,] 0]) {}
        }
        foreach name [array names array] {
            if {![array exist $name]} {array unset data $name,*}
        }
        if {[array size data] > $global::realTimeHistory(maximumSamples)} {   ;# note: "array size" implementation scans whole array
            set names [array names data]
            foreach name $names {
                lappend instants [lindex [split $name ,] end]
            }
            set limit [lindex [lsort -integer $instants] end-$global::realTimeHistory(maximumSamples)]
            foreach name $names instant $instants {
                if {$instant <= $limit} {array unset data $name}
            }
        }
        after [expr {$global::realTimeHistory(cleanPeriod) * 1000}] history::clean
    }
    clean                                                                                                   ;# boot clean up process

}
