import sys
import matplotlib.pyplot as plt
import json
import threading

def read_data():
    try:
        return json.load(open("/tmp/values.pickle", 'r'))
    except:
        return (0.0, {})

def write_data(values):
    json.dump(values, open("/tmp/values.pickle", 'w'))

plt.ion()
plt.figure()

old_time, d = read_data()
plt.pause(0.01)
l = sys.stdin.readline()
time, _ = l.split(" ", 1)
time = float(time)

maps = {}

if time <= old_time:
    # Overwrites current values, so flush
    d = {}
    plt.legend()
else:
    for key in d:
        maps[key], = plt.plot(d[key][0], d[key][1])
        maps[key].set_label(key)
    plt.legend()

first = l

while 1:
    if first is not None:
        l = first
        first = None
    else:
        l = sys.stdin.readline()

    if l == "CLOSE":
        import sys
        sys.exit(0)
    elif l == "ALGEBRAIC_LOOP":
        continue
    time, key, value = l.split(" ")
    time = float(time)
    try:
        value = float(value)
    except:
        # Value is not a number, so we work with discrete states, just ignore!
        pass
        value = value.strip()

    if key not in maps:
        maps[key], = plt.plot([], [])
        maps[key].set_label(key)
        plt.legend()

    if key not in d:
        d[key] = ([], [])

    d[key][0].append(time)
    d[key][1].append(value)

    if isinstance(value, str) and value not in d[key][1][:-1]:
        for key in d:
            prev_color = maps[key].get_color()
            maps[key].remove()
            maps[key], = plt.plot(d[key][0], d[key][1], c=prev_color)
            maps[key].set_label(key)
        plt.legend()

    maps[key].set_xdata(d[key][0])
    maps[key].set_ydata(d[key][1])
    plt.gca().set_xlim([min(d[key][0]), max(d[key][0])])
    plt.pause(0.01)
    write_data((0.0, d))
