# coding=utf-8
import matplotlib
matplotlib.use('WxAgg')
import logging
import pygame
import yaml
import os
import sys
from matplotlib import animation
from GUI.Scope import ScopePanel, TrendScope, DumbScope
from monitor.ComediObjects import ComediStreamer
import wx

configFile = u"""
comedi:
  device: /dev/comedi0  # device name
  sub-device: 0
  sample-rate: 1000  # in Hz
  channels:
    - chan-1:  # EKG
      channel-id: 0  # the comedi channel number
      gain: 0  # the gain of the board
      ref: 0   # reference
"""

# class ScopePanel(wx.Panel):
#     def __init__(self, parent):
#         super(ScopePanel, self).__init__(parent)
#         self.figure = Figure()
#         self.axes = self.figure.add_subplot(111)
#         self.lines = []
#         self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
#         self.sizer = wx.BoxSizer(wx.VERTICAL)
#         self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
#         self.SetSizer(self.sizer)
#         self.Fit()
#
#     def clear(self):
#         self.lines = self.axes.plot([], [])
#         return self.lines
#
#     def append(self, data):
#         logging.debug("in ScopePanel.append(data=%s)", data.shape)
#
#         return self.lines


if __name__ == "__main__":
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    # init mixer
    pygame.mixer.init(44100, -16, 2, 2048)

    currentPath = os.path.dirname(os.path.realpath(sys.argv[0]))
    with open(os.path.join(currentPath, 'PhysioMonitor.yml'), 'r') as stream:
        config = yaml.safe_load(stream)
    app = wx.App()
    fr = wx.Frame(None, title='test')
    sz = wx.BoxSizer()
    panel = ScopePanel(fr)
    sz.Add(panel, 1, wx.EXPAND)
    scopeList = []
    for chan in config['comedi']['channels']:
        func = None
        scope = DumbScope(panel.figure, windowSize=chan['window-size'],
                           dt=1. / config['comedi']['sample-rate'], remanence=chan['remanence'],
                           linecolor=chan['line-color'], linewidth=chan['line-width'], scaling=chan['scale'],
                           offset=chan['offset'], title=chan['label'], units=chan['units'],
                           triggerMode=chan['trigger-mode'], autoDefineThreshold=chan['auto-define-threshold'],
                           thresholdWindow=chan['threshold-window'],
                           relThresholdLevel=chan['relative-threshold-level'],
                           thresholdLevel=chan['threshold-level'], autoscale=chan['autoscale'], ymin=chan['ymin'],
                           ymax=chan['ymax'], trendMin=chan['trend-ymin'], trendMax=chan['trend-ymax'],
                           trendWidth=chan['trend-width'], trendPeriod=chan['trend-period'], trendFunction=func,
                           trendFuncArgs=chan['trend-function-args'], trendFormat=chan['trend-format'],
                           trendUnits=chan['trend-units'],
                           alarmEnabled=chan['alarm-enabled'], alarmLow=chan['alarm-low'],
                           alarmHigh=chan['alarm-high'], alarmSoundFile=chan['alarm-sound-file'])
        scopeList.append(scope)
    panel.addScopes(scopeList)

    a = ComediStreamer(config)
    a.start()

    ani = animation.FuncAnimation(panel.figure, panel.append, frames=a.iterator, init_func=panel.reset, interval=1,
                                  blit=True)

    fr.SetSizerAndFit(sz)
    fr.Show()
    app.MainLoop()
