import pyqtgraph as pg

# import numpy as np
import logging
import json

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QListWidget, QTabWidget, QGridLayout

from GUI.scope import ScopeLayoutWidget, PagedScope
from monitor.sampling import SurgeryFileStreamer

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

with open('./PhysioMonitor.json', 'r') as stream:
    config = json.load(stream)

# Always start by initializing Qt (only once per application)
app = QApplication([])

# Define a top-level widget to hold everything
w = QWidget()

# Create some widgets to be placed inside
btn = QPushButton('press me')
text = QLineEdit('enter text')
listw = QListWidget()
notebook = QTabWidget()
graphLayout = ScopeLayoutWidget()

# Create a grid _vbox to manage the widgets size and position
layout = QGridLayout()
w.setLayout(layout)

# Add widgets to the _vbox in their proper positions
layout.addWidget(btn, 0, 0)  # button goes in upper-left
layout.addWidget(text, 1, 0)  # text edit goes in middle-left
layout.addWidget(listw, 2, 0)  # list widget goes in bottom-left
layout.addWidget(notebook, 0, 1, 3, 1)  # plot goes on right side, spanning 3 rows
notebook.addTab(graphLayout, "Graphs")
notebook.addTab(QWidget(), "Log")

for i, chan in enumerate(config['comedi']['channels']):
    plot = PagedScope(
        sampleFreq=config['comedi']['sample-rate'],
        windowSize=chan['window-size'],
        linecolor=chan['line-color'],
        linewidth=chan['line-width'],
        scaling=chan['scale'],
        offset=chan['offset'],
        title=chan['label'],
        units=chan['units'],
        autoscale=chan['autoscale'],
        ymin=chan['ymin'],
        ymax=chan['ymax'],
        remanence=chan['remanence'],
        trigMode=chan['trigger-mode'],
        trigLevel=chan['trigger-level'],
        autoTrigLevel=chan['auto-trigger-level'],
        trendWindowSize=chan['trend-window-size'],
        trendPeriod=chan["trend-period"],
        trendFunction=chan["trend-function"],
        trendFuncKwargs=chan["trend-function-args"],
        trendUnits=chan["trend-units"],
        trendAutoscale=chan["trend-autoscale"],
        trendYmin=chan["trend-ymin"],
        trendYmax=chan["trend-ymax"],
        alarmEnabled=chan['alarm-enabled'],
        alarmLow=chan['alarm-low'],
        alarmHigh=chan['alarm-high'],
        alarmSoundFile=chan['alarm-sound-file']
    )
    graphLayout.addItem(plot, i, 1)

# Display the widget as a new window
w.show()

a = SurgeryFileStreamer(nChan=len(config['comedi']['channels']), filename="./media/surgery.txt", pointsToReturn=None)
# a = SurgeryFileStreamer(config=config)
a.start()


def update():
    global graphLayout
    data = a.read()
    graphLayout.append(data)


timer = pg.QtCore.QTimer()
# noinspection PyUnresolvedReferences
timer.timeout.connect(update)
timer.start(50)
# noinspection PyUnresolvedReferences
# btn.clicked.connect(update)

# Start the Qt event loop
app.exec_()
