import threading
import time
    
class Block:

    def __init__(self,value,validity=0.0,priority=0.0):
        self.value = value
        self.validity = 0 if validity == 0.0 else validity + time.time()
        self.priority = priority
        
    def valid(self):
        if not self.value:
            return False
        return self.validity == 0 or self.validity > time.time()

    def set(self,value,validity,priority):
        if (not self.valid()) or self.priority <= priority:
            self.value = value;
            self.validity = 0 if validity == 0.0 else validity + time.time()
            self.priority = priority
    
class Space:
    
    blocks = dict()
    
    def __init__(self):
        pass
        
    def read(name, dflt):
        if name in Space.blocks:
            if Space.blocks[name].valid():
                return Space.blocks[name].value
            else:
                return dflt
        else:
            return dflt
    
    def write(name, value, validity=0.0, priority=0.0):
        #print(name,"=",value)
        if name in Space.blocks:
            Space.blocks[name].set(value,validity,priority)
        else:
            Space.blocks[name] = Block(value,validity,priority)


class Module:

    def __init__(self,name,timing):
        self.timing = timing
        self.stopped = False
        self.t = threading.Thread(name=name, target=self.run)
        self.t.start()
        
    def run(self):
        while not self.stopped:
            self.behavior()
            time.sleep(self.timing)
        
    def behavior(self): # to be overiden
        print('I am alive')
        
    def stop(self):
        self.stopped = True
       
if __name__ == "__main__":

    Space.write("a",3,validity=2,priority=1)
    Space.write("a",4,priority=0)
    time.sleep(1)
    print(Space.read("a",-1))
    time.sleep(1.1)
    print(Space.read("a",-1))
    Space.write("a",4,priority=0)
    print(Space.read("a",-1))
    
    m = Module("A",0.5)
    time.sleep(4)
    m.stop()
    