from pypdevs.DEVS import AtomicDEVS, CoupledDEVS
from pypdevs.simulator import Simulator
from pypdevs.infinity import INFINITY

import Tkinter as tk

class Replayer(AtomicDEVS, tk.Toplevel):
    def __init__(self, width, height):
        tk.Toplevel.__init__(self)
        AtomicDEVS.__init__(self, "Replayer")
        
        self.geometry('{}x{}'.format(800, 600))
				
        CANVAS_SIZE_TUPLE = (0, 0, self.winfo_screenwidth(), self.winfo_screenheight())
        self.canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE)
        self.canvas.pack(expand = True, fill=tk.BOTH)
        self.text = self.canvas.create_text(5, 5, anchor='nw', text="TIME: %s" % 0.0)
        
        self.f = open('sim_output', 'r')
        
        self.curr_time = 0.0
        self.id_mapping = {}
        self.colors = {}
        self.next_time = None
        
        self.title('Replayer')
        self.attributes("-topmost", True)
    
    def timeAdvance(self):
        if self.next_time is None:
            l = self.f.readline()
            self.next_time = float(l.split(" ")[1])
        return self.next_time - self.curr_time
    
    def intTransition(self):
        self.curr_time = self.next_time
        l = self.f.readline()
        while not l.startswith("time"):
            if l.startswith('positions'):
                self.canvas.delete("all")
                self.text = self.canvas.create_text(5, 5, anchor='nw', text="TIME: %s" % self.curr_time)
                self.id_mapping.clear()
                iter_l = self.f.readline()
                while not iter_l.startswith("endpositions"):
                    splitted = iter_l.split(" ")
                    ball_id = int(splitted[0])
                    x = float(splitted[1])
                    y = float(splitted[2])
                    r = float(splitted[3])
                    color = self.colors.setdefault(ball_id, "red")
                    self.id_mapping[ball_id] = self.canvas.create_oval(x, y, x + (r * 2), y + (r * 2), fill=color)
                    iter_l = self.f.readline()
            elif l.startswith('color'):
                iter_l = self.f.readline()
                while not iter_l.startswith("endcolor"):
                    splitted = iter_l.split(" ")
                    ball_id = int(splitted[0])
                    color = splitted[1][:-1]
                    if ball_id in self.id_mapping:
                        self.canvas.itemconfig(self.id_mapping[ball_id], fill=color)
                        self.colors[ball_id] = color
                    iter_l = self.f.readline()
            l = self.f.readline()
        self.next_time = float(l.split(" ")[1])

if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    
    ''' instantiate DEVS model '''
    model = Replayer(800, 600)
    
    ''' simulator setup '''
    sim = Simulator(model)
    sim.setRealTime(True)
    sim.setRealTimeInputFile(None)
    sim.setRealTimePorts({})
    sim.setRealTimePlatformTk(root)
    
    ''' run simulation + visualization '''
    sim.simulate()
    root.mainloop()