#!/usr/bin/env python3
import sys
from pathlib import Path
# Add import path for inplace usage
sys.path.insert(0, str(Path(__file__).absolute().parents[1]))

from frappy.client.interactive import Client
from frappy_psi.iqplot import Plot
import numpy as np
import matplotlib.pyplot as plt


if len(sys.argv) < 2:
    print('Usage: peus-plot <maxY>')


def get_modules(name):
    return list(filter(None, (globals().get(name % i) for i in range(10))))


secnode = Client('pc13252:5000')
time_size = {'time', 'size'}
int_mods = [u] + get_modules('roi%d')
t_rois = get_modules('roi%d')
i_rois = get_modules('roi%di')
q_rois = get_modules('roi%dq')

maxx = None
if len(sys.argv) > 1:
    maxy = float(sys.argv[1])
    if len(sys.argv) > 2:
        maxx = float(sys.argv[2])
else:
    maxy = 0.02


iqplot = Plot(maxy, maxx)

for i in range(99):
    pass

try:
    while True:
        curves = np.array(u.get_curves())
        iqplot.plot(curves,
                    rois=[(r.time - r.size * 0.5, r.time + r.size * 0.5) for r in int_mods],
                    average=([r.time for r in t_rois],
                             [r.value for r in i_rois],
                             [r.value for r in q_rois]))
        if not iqplot.pause(0.5):
            break
except KeyboardInterrupt:
    iqplot.close()
